Python 3.x 使用多处理写入同一文件(避免锁定)

Python 3.x 使用多处理写入同一文件(避免锁定),python-3.x,multiprocessing,locking,Python 3.x,Multiprocessing,Locking,我正在使用多处理在多个csv文件上运行脚本。 如果一行与正则表达式匹配,它会将该行写入新文件(新文件名等于match)。 我注意到从不同进程(文件锁)写入同一个文件时出现问题。我怎样才能解决这个问题 我的代码: import re import glob import os import multiprocessing pattern ='abc|def|ghi|jkl|mno' regex = re.compile(pattern, re.IGNORECASE) def process_f

我正在使用多处理在多个csv文件上运行脚本。
如果一行与正则表达式匹配,它会将该行写入新文件(新文件名等于match)。
我注意到从不同进程(文件锁)写入同一个文件时出现问题。我怎样才能解决这个问题

我的代码:

import re
import glob
import os
import multiprocessing

pattern ='abc|def|ghi|jkl|mno'
regex = re.compile(pattern, re.IGNORECASE)

def process_files (file):
    res_path = r'd:\results'
    with open(file, 'r+', buffering=1) as ifile:
        for line in ifile:
            matches = set(regex.findall(line))
            for match in matches:
                res_file = os.path.join(res_path, match + '.csv') 
                with open(res_file, 'a') as rf:
                    rf.write(line)

def main():

    p = multiprocessing.Pool()
    for file in glob.iglob(r'D:\csv_files\**\*.csv', recursive=True):
        p.apply_async(process, [file]) 

    p.close()
    p.join()

if __name__ == '__main__':
    main()

提前谢谢

使每个子流程的文件名唯一:

def process_files (file, id):
    res_path = r'd:\results'
    for line in file:
        matches = set(regex.findall(line))
        for match in matches:
            filename = "{}_{}.csv".format(match, id)
            res_file = os.path.join(res_path, filename) 
            with open(res_file, 'a') as rf:
                rf.write(line)

def main():

    p = multiprocessing.Pool()
    for id, file in enumerate(glob.iglob(r'D:\csv_files\**\*.csv', recursive=True)):
        p.apply_async(process, [file, id]) 
然后,您必须添加一些代码以将不同的“u.csv”文件合并到单个“.csv”文件中


要避免在同一个文件上并发写操作—要么没有文件锁,最终导致数据损坏,要么有文件锁,然后会减慢进程,这就破坏了并行化的整体意义。

注意:您从未真正打开文件以写入
进程\文件
,它只是一个带有路径的字符串(由
glob.iglob
生成)复制粘贴错误。道歉。。。有点太快了。编辑它。