E
E
Evgeny Kolesov2018-04-16 12:23:26
Python
Evgeny Kolesov, 2018-04-16 12:23:26

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)

With while True, everything goes well, but with it for char in open('test.txt').read()gives a syntax error. Tell me where is the mistake?
PS as I understand it, the code works even without the last line with for, opens the file and reads it line by line, then why is this line needed for char in open('test.txt').read()?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DDDsa, 2018-04-16
@jaimekoyl

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 question

Ask a Question

731 491 924 answers to any question