【发布时间】:2019-02-04 03:38:55
【问题描述】:
我有一个简单的任务。需要为大量文件运行特定功能。此任务可以轻松并行化。
这是工作代码:
# filelist is the directory containing two file, a.txt and b.txt.
# a.txt is the first file, b.xt is the second file
# I pass a file that lits the names of the two files to the main program
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import sys
def translate(filename):
print(filename)
f = open(filename, "r")
g = open(filename + ".x", , "w")
for line in f:
g.write(line)
def main(path_to_file_with_list):
futures = []
with ProcessPoolExecutor(max_workers=8) as executor:
for filename in Path(path_to_file_with_list).open():
executor.submit(translate, "filelist/" + filename)
for future in as_completed(futures):
future.result()
if __name__ == "__main__":
main(sys.argv[1])
但是,不会创建新文件,即该文件夹不包含 a.txt.x 和 b.txt.x 文件。
上面的代码有什么问题,我怎样才能让它工作?
谢谢。
【问题讨论】:
-
您的程序包含打印语句。你有任何输出吗?
-
对文件进行迭代会为您提供文件的行,包括行尾 - 因此您尝试打开名称包含换行符的文件,这实际上不太可能存在。
-
你也没有关闭文件。如果你不关闭“g”,你可能不会得到任何输出。如果您使用“with”语句打开 f 和 g,它们将始终在块的末尾关闭。
-
futures在main的第二个循环中仍然是一个空列表 -
@PaulCornelius 是的,打印语句工作正常
标签: python python-3.x python-2.7 multiprocessing python-multiprocessing