如何在文件读取期间改回一行
在我的代码中,我有一个像这样的行长度打印:
line = file.readline()
print("length = ", len(line))
之后我开始通过执行以下操作来扫描行:
for i in range(len(line)):
if(file.read(1) == 'b'):
print("letter 'b' found.")
问题是 for
循环开始读取文件的第 2 行。 如何让它从第 1 行开始读取而不关闭并重新打开文件?
In my code I have a line length print like this:
line = file.readline()
print("length = ", len(line))
after that I start to scan the lines by doing this:
for i in range(len(line)):
if(file.read(1) == 'b'):
print("letter 'b' found.")
The problem is that the for
loop starts reading on line 2 of the file.
How can I make it start reading at line 1 without closing and reopening the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以使用 file.seek 移动下一次读取的位置,但效率很低。您已经阅读了该行,因此您可以直接处理
line
无需再次阅读。It is possible to use
file.seek
to move the position of the next read, but that's inefficient. You've already read in the line, so you can just processline
without having to read it in a second time.看来你需要专门处理第一行。
It seems that you need to handle the first line specially.
听起来你想要这样的东西:
或者如果你只需要号码:
It sounds like you want something like this:
or if you just need the number: