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