Python-如何一次读取一个字符的文件?
我正在学习python文件处理。我尝试使用此代码一次读取一个字符Python-如何一次读取一个字符的文件?,python,python-2.7,file-handling,Python,Python 2.7,File Handling,我正在学习python文件处理。我尝试使用此代码一次读取一个字符 f = open('test.dat', 'r') while (ch=f.read(1)): print ch 为什么它不起作用 这里是错误消息 C:\Python27\python.exe "C:/Users/X/PycharmProjects/Learning Python/01.py" File "C:/Users/X/PycharmProjects/Learning Python/01.py", line 4
f = open('test.dat', 'r')
while (ch=f.read(1)):
print ch
为什么它不起作用
这里是错误消息
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
语法有点不正确,while语句中的赋值语法无效:
f = open('test.dat', 'r')
while True:
ch=f.read(1)
if not ch: break
print ch
这将启动while循环,并在没有字符可读取时中断它!试试看。您的语法有点错误,while语句中的赋值语法无效:
f = open('test.dat', 'r')
while True:
ch=f.read(1)
if not ch: break
print ch
这将启动while循环,并在没有字符可读取时中断它!试一试。您可以使用两种形式的iter作为
while
循环的替代:
for ch in iter(lambda: f.read(1), ''):
print ch
您可以使用两种形式的
iter
作为while
循环的替代:
for ch in iter(lambda: f.read(1), ''):
print ch
一次一个字符还是一个字节?一次一个字符还是一个字节?