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

允我心安 提交于 2019-12-24 12:25:54

问题


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:\Python27\python.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

回答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)
    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.




回答2:


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


来源:https://stackoverflow.com/questions/21915501/python-how-to-read-file-one-character-at-a-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!