Python-如何一次读取一个字符的文件? [英] Python - How to read file one character at a time?

查看:168
本文介绍了Python-如何一次读取一个字符的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习python文件处理.我尝试使用此代码一次读取一个字符

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

为什么不起作用

这是错误消息

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语句中指定的语法无效:

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

这将启动while循环,并在没有字符可读取时将其中断!试试看.

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

这篇关于Python-如何一次读取一个字符的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆