0

在 python 中,我试图编写一个脚本来编辑文本文件,然后运行使用这些文本文件的可执行文件。它基本上需要 1)打开和读取/写入文本文件,以及 2)使用我刚刚在 bash 命令中编写的文件。这是一个简单的例子:

import subprocess

# write file
a = ['1\n','2\n','3\n','4\n','5th and final line']
f = open('junk01.txt', 'wb')
f.writelines(a)
f.close

# show file
subprocess.call('cat junk01.txt', shell=True)

由于某种原因,该subprocess.call命令没有显示 junk01.txt 文件的内容。但是,在我运行此代码并输入cat junk01.txtbash 后,文件已正确写入。同样,我发现在我打开、写入和关闭文本文件然后尝试在可执行文件中使用它之后,该文件还没有被写入。关于为什么会这样以及我能做些什么来解决它的任何解释?

4

2 回答 2

9

通过实际调用 close() 方法来关闭文件。这将隐式地将缓冲区刷新到磁盘。

f.close()

而不是

f.close     #this probably doesn't do anything, but if there was no close method it would raise an error.
于 2009-03-11T19:18:45.790 回答
0

尽管第一个答案绝对是正确和正确的,但您也可以将 f 设置为 None 而不是按如下方式完成:

import subprocess

# write file
a = ['1\n','2\n','3\n','4\n','5th and final line\n']
f = open('junk01.txt', 'wb')
f.writelines(a)
f = None
# show file
subprocess.call('cat junk01.txt', shell=True)

~

将 f 设置为 None 会使变量停止服务并导致文件被隐式关闭而不是被显式关闭(如在第一个首选示例中)我不提倡这种编写代码的风格,因为它有点草率,我只是提到它作为替代解决方案。

[centos@localhost ~/test/stack]$  python 1.py
1
2
3
4
5th and final line
[centos@localhost ~/test/stack]$  
于 2013-12-12T13:08:19.267 回答