Answer the question
In order to leave comments, you need to log in
Why can't I read the file line by line?
You need to read the file line by line and here is the actual code (taken from educational literature)
file = open('/home/blizz/Desktop/test.txt', 'r')
while True:
char = file.read(1)
if not char: break
print(char)
for char in: open('test.txt').read()
print(char)
for char in open('test.txt').read()
gives a syntax error. Tell me where is the mistake? for char in open('test.txt').read()
?
Answer the question
In order to leave comments, you need to log in
First, you don't need a colon after in.
Secondly, in the code you both times read not line by line, but character by character. read()
returns a string containing the entire contents of the file. You need a method readlines()
, it will return a list of lines in the file.
But in python there is a way to read a file line by line without cramming the entire file into memory, just loop over the open file for line in file
.
And the best is like this:
with open('test.txt', 'r') as f:
for l in f:
print(l)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question