【发布时间】:2012-08-12 14:41:32
【问题描述】:
我正在编写一个应用程序,它可以从多个线程将行附加到同一个文件。
我遇到了一个问题,其中一些行被附加而没有新行。
有什么解决办法吗?
class PathThread(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def printfiles(self, p):
for path, dirs, files in os.walk(p):
for f in files:
print(f, file=output)
def run(self):
while True:
path = self.queue.get()
self.printfiles(path)
self.queue.task_done()
pathqueue = Queue.Queue()
paths = getThisFromSomeWhere()
output = codecs.open('file', 'a')
# spawn threads
for i in range(0, 5):
t = PathThread(pathqueue)
t.setDaemon(True)
t.start()
# add paths to queue
for path in paths:
pathqueue.put(path)
# wait for queue to get empty
pathqueue.join()
【问题讨论】:
-
贴一些代码,会有帮助的。
-
写入时检查文件最后一个字符是否为换行符。如果不是,请附加一个。当然,这需要用 r+ 而不是 a 打开,这可能不是你想要的。
标签: python multithreading python-multithreading