重新读取打开的文件 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17021863/
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
Re-read an open file Python
提问by Ben Cartwright
I have a script that reads a file and then completes tests based on that file however I am running into a problem because the file reloads after one hour and I cannot get the script to re-read the file after or at that point in time.
我有一个脚本,它读取一个文件,然后根据该文件完成测试,但是我遇到了一个问题,因为该文件在一小时后重新加载,我无法让脚本在那个时间点之后或在那个时间点重新读取该文件。
So:
所以:
- GETS NEW FILE TO READ
- Reads file
- performs tests on file
- GET NEW FILE TO READ (with same name - but that can change if it is part of a solution)
- Reads new file
- perform same tests on new file
- 获取新文件以供阅读
- 读取文件
- 对文件执行测试
- 获取要阅读的新文件(具有相同名称 - 但如果它是解决方案的一部分,则可以更改)
- 读取新文件
- 对新文件执行相同的测试
Can anyone suggest a way to get Python to re-read the file?
任何人都可以建议一种让 Python 重新读取文件的方法吗?
采纳答案by John La Rooy
Either seekto the beginning of the file
要么seek到文件的开头
with open(...) as fin:
fin.read() # read first time
fin.seek(0) # offset of 0
fin.read() # read again
or open the file again (I'd prefer this way since you are otherwise keeping the file open for an hour doing nothing between passes)
或再次打开文件(我更喜欢这种方式,因为否则您将文件打开一个小时,两次通过之间什么都不做)
with open(...) as fin:
fin.read() # read first time
with open(...) as fin:
fin.read() # read again
Putting this together
把这个放在一起
while True:
with open(...) as fin:
for line in fin:
# do something
time.sleep(3600)
回答by Konstantin Dinev
You can move the cursor to the beginning of the file the following way:
您可以通过以下方式将光标移动到文件的开头:
file.seek(0)
Then you can successfully read it.
然后就可以成功读取了。

