Python – How to read file one character at a time?

Question:

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 Error message

C:Python27python.exe "C:/Users/X/PycharmProjects/Learning Python/01.py"
File "C:/Users/X/PycharmProjects/Learning Python/01.py", line 4
while (ch=f.read(1)):
         ^
SyntaxError: invalid syntax

Process finished with exit code 1
Asked By: Cody

||

Answers:

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)
    if not ch: break
    print ch

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

Answered By: binaryatrocity

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

for ch in iter(lambda: f.read(1), ''):
    print ch
Answered By: Jon Clements

For python 3.8+ you can just do this:

with open("test.dat", "r") as f:
    while ch := f.read(1):
        ...

The walrus operator was added in Python 3.8 and it lets you use assignment as an expression!

Answered By: RGBCube
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.