Python从磁盘刷新文件 [英] Python refresh file from disk
问题描述
我有一个调用系统程序的python脚本,并从文件 out.txt
中读取输出,对该输出执行操作并循环。但是,它不起作用,并且仔细调查显示python脚本只打开 out.txt
一次,然后继续读取该旧副本。如何让python脚本在每次迭代时重新读取文件?我在这里看到了一个类似的问题,但它是关于一个与程序一起运行的python脚本,而不是调用它,并且该解决方案不起作用。我尝试在循环之前关闭文件,但它没有做任何事情。
I have a python script that calls a system program and reads the output from a file out.txt
, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens out.txt
once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.
编辑:
我已经尝试关闭并打开,但它没有用。这是代码:
I already tried closing and opening, it didn't work. Here's the code:
import subprocess, os, sys
filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo.write(file.read().rstrip())
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0
while True:
subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output
foo.write('\n'+output)
out.close()
else:
break
print "There are ", numSolutions, " solutions."
推荐答案
你需要刷新 foo
以便外部程序可以看到其最新的更改。写入文件时,数据将在本地进程中缓冲,并以较大的块发送到系统。这样做是因为更新系统文件相对昂贵。在您的情况下,您需要强制刷新数据,以便minisat可以看到它。
You need to flush foo
so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it.
foo.write('\n'+output)
foo.flush()
这篇关于Python从磁盘刷新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!