我试图执行的python代码必须将两个不同的变量写入一个文件。我使用Condor来加快我的进程,这意味着python代码被执行同步。我定义的写函数是:
with open('output.txt', 'a') as results_file:
results_file.write(str(gc_count) + '\n')
results_file.write(str(length) + '\n')
results_file.close()但不幸的是,该文件以某种方式一直覆盖结果。有人能帮助我如何用Condor将变量写入文本文件吗?
发布于 2017-02-24 14:09:45
即使将文件模式设置为追加,文件中的并发写入也会导致数据损坏。
在多线程环境中,可以使用threading.Lock对象保护写调用:
import threading
l = threading.Lock() # l must be a global variable or a member of some class然后,在写入时,请求对锁的许可,并在写入文件时释放它:
l.acquire()
with open('output.txt', 'a') as results_file:
results_file.write(str(gc_count) + '\n')
results_file.write(str(length) + '\n')
l.release()(旁白:您不需要文件上下文管理器中的最后一个close )
https://stackoverflow.com/questions/42439964
复制相似问题