Python保存在另一个编辑器中后无法写入文件



我有一个连续运行的python文件,偶尔将其写入文件的键盘输入。

但是,如果我在另一个编辑器中编辑文件(例如使用sed或head或gedit(,然后再保存,我的python程序将不再写入文件,即使(使用GEDIT(我退出了编辑。

能够继续写入文件的正确方法是什么?这是一个示例

import sys
f = open('tmp.txt', 'ab')
while 1:
   raw_input()
   f.write('this is a testn')
    f.flush()
f.close()

示例:

python tmp.py
(enter input) #writes line to file
[ in a separate terminal ] sed -i '$ d' tmp.txt #deletes last line in file
(enter input to python in terminal) #no longer writes to file

您的操作系统在文件上管理读/写访问。当您首先获得对循环外部文件的写作访问时,一旦通过另一个过程或线程将其收集到循环中,您将永远不会将其恢复。因此,设置循环内的文件对象。

import sys
while True :
    raw_input()
    with open('tmp.txt', 'ab') as f :
        f.write('this is a testn')

对于文件对象,建议使用上下文管理器( with statement(。它将自动打开并关闭对象。

import sys
while True :
    with open('tmp.txt', 'ab') as f :
        f.write('this is a testn')

最新更新