在Python程序中,为何在写入后无法立即查看文件内容?
我尝试在创建并写入一个文件后,使用Popen()来查看这个文件的内容。但是没有成功。打印出来的结果是两个空的元组('','')。这是为什么呢?我使用了重命名来确保写入操作是原子的,具体可以参考这里的讨论。
#!/usr/bin/env python
import sys,os,subprocess
def run(cmd):
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
if p.returncode:
print "failed with code: %s" % str(p.returncode)
return p.communicate()
except OSError:
print "OSError"
def main(argv):
t = "alice in wonderland"
fd = open("__q", "w"); fd.write(t); fd.close; os.rename("__q","_q")
p = run(["cat", "_q"])
print p
main(sys.argv)
1 个回答
11
你没有调用 close
。应该用 fd.close()
(你忘记加括号了,这样才能真正调用这个函数)。其实可以通过使用 with
语句来避免这个问题:
with open("__q", "w") as fd:
fd.write(t)
# will automatically be closed here