本文介绍了无法使用Python多重处理写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from itertools import product

f = open('filename.txt', 'a')

def worker(i, j):
    print i,j
    f.write("%s\t%s\n"%(i,j))
    return

def main():
    a_list = ['1', '2', '3', '4', '5'] #5 item
    b_list = ['6', '7', '8'] #3 item
    # Total 5*3=15 combinations

    from multiprocessing import Pool
    pool = Pool(processes=4)
    results = [pool.apply_async(worker, args=(i, j)) for i, j in product(a_list, b_list)]
    output = [p.get() for p in results]

main()
f.close()

这是我试图运行的代码,并将结果存储在txt文件中,但是我无法找出为什么它没有写,尽管它在终端中打印.任何帮助将不胜感激.

this is the code I'm trying to run and store result in a txt file but I'm unable to findout why this isn't writing, although its printing in terminal. any help would be appreciated.

推荐答案

f.write(...)语句后添加f.flush()

这篇关于无法使用Python多重处理写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:24