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

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值