我想並行化一個文件過濾操作,其中每個過濾器是一個大的正則表達式,因此整個事情需要時間來運行。該文件本身大約100GB。單進程的版本是這樣的:python使用多進程來過濾海量文件
def func(line):
# simple function as an example
for i in range(10**7):
pass
return len(line) % 2 == 0
with open('input.txt') as in_sr, open('output.txt', 'w') as out_sr:
for line in input:
if func(line):
out_sr.write(line)
我嘗試使用multiprocessing
的imap
但給人ValueError: I/O operation on closed file.
我認爲迭代被複制到每一個過程,但不是所有的進程有處理打開。
有沒有辦法做到這一點使用multiprocessing
,最好是利用池?
如果__name__ =='__main __':'?你必須保持線條的秩序? – eph
@eph是的行必須與輸入文件的順序相同。在我的真實代碼中,'with'是函數中的某個地方。 – simonzack
什麼是你的文件和正則表達式?在命令行或其他文件處理工具上使用awk會更容易嗎? – DainDwarf