如何在python中开始文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40004672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to go the start of file in python?
提问by Suraj Nagabhushana Ponnaganti
I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' .
我是 python 的新手,我正在学习一些基本的文件读取内容。我正在尝试读取一个文件并计算新行的数量,并打印以 'From:' 开头的行。
This is the code I have for that:
这是我的代码:
fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print count
for line in fhand:
if line.startswith('From: '):
print line
I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file?
我知道我可以在一个循环中完成此操作,但我正在尝试在这里学习一些东西。一旦执行第一个循环,'line' 就位于文件的末尾。因此,当它运行第二个循环时,它不会打印任何内容。我试过放入 line = 0,它不起作用。我如何回到文件的开头?
Thank you for your help.
感谢您的帮助。
回答by MooingRawr
回答by MMF
Try this out :
试试这个:
with open('mbox.txt') as f:
count = 0
for l in f.readlines():
count += 1
if l.startswith('From: '):
print l
To get back to start of file use seek(0)
回到文件使用的开始 seek(0)