Skip to content Skip to sidebar Skip to footer

Python - How To Read File One Character At A Time?

I am learning python file handling. I tried this code to read one character at a time f = open('test.dat', 'r') while (ch=f.read(1)): print ch Why it's not working Here is Er

Solution 1:

Your syntax is a bit off, your assignment inside the while statement is invalid syntax:

f = open('test.dat', 'r')
while True:
    ch=f.read(1)
    ifnot ch: breakprint ch

This will start the while loop, and break it when there are no characters left to read! Give it a try.

Solution 2:

You can use the two form version of iter as an alternative to a while loop:

for ch initer(lambda: f.read(1), ''):
    print ch

Post a Comment for "Python - How To Read File One Character At A Time?"