[PYTHON] Read file

1


s = """\
AAA
BBB
CCC
DDD
"""

with open('test.txt', 'w') as f:
    f.write(s)

with open('test.txt', 'r') as f:
    while True:
        line = f.readline()
        print(line, end="")
        
        if not line:
            break

Execution result of 1


AAA
BBB
CCC
DDD

python


with open('test.txt', 'w') as f:
    f.write(s)

And the contents of test.txt AAA BBB CCC DDD A text file is created.

And

python


with open('test.txt', 'r') as f:

Read the contents of test.txt as f with

python


while True:
        line = f.readline()
        print(line, end="")

        if not line:
            break

so, The contents of test.txt are stored line by line in the variable line and output. Do not lose the contents of the line, loop it, Break when it's gone.

2


s = """\
AAA
BBB
CCC
DDD
"""

with open('test.txt', 'w') as f:
    f.write(s)

with open('test.txt', 'r') as f:
    while True:
        chunk = 2
        line = f.read(chunk)
        print(line)
        
        if not line:
            break

Execution result of 2


AA
A

BB
B

CC
C

DD
D

Two characters are output at a time.

A2 A and line break B2 B and line break C2 C and line break D2 D and line break

Recommended Posts

Read file
Read CSV file: pandas
File read overhead measurement
Read Python csv file
Read and write csv file
Read and write a file
Write and read a file
File matching
File creation
File operations
Read pid.h
[Note] Read a file from another directory
Read CSV file with python (Download & parse CSV file)
Let's read the RINEX file with Python ①
Read the file line by line in Python
Read the file line by line in Python
Read the file by specifying the character code.
Read a character data file with numpy
[python] Read html file and practice scraping
[Python] Read the specified line in the file
[Automation] Read mail (msg file) with Python
Script python file
How to read a CSV file with Python 2/3
UNIX file descriptor
syslog file rename
[Python] How to read excel file with pandas
Duplicate file removal
Read table data in PDF file with Python
Read pandas data
Python file processing
Linux command [read]
Read PNG chunks
[Linux] File search
[SQLAlchemy] Read data
Have pandas read the zip file on the web
astropy: fits file
Read line by line from a file with Python
How to read a file in a different directory
Nginx config file
[python] Read data
Template of python script to read the contents of the file
Read the csv file and display it in the browser
Read the xml file by referring to the Python tutorial
Read QR code from image file with Python (Mac)
Read logging settings from an external file in Flask
Read json file with Python, format it, and output json