Python如何使用多处理来读写不同的文件

2024-10-03 11:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个文件,我想阅读这些文件,过滤一些关键字,并把他们写入不同的文件。我使用Process(),结果发现处理readwrite函数需要更多的时间。 我需要分开读写两个函数吗?如何一次读取多个文件,并将不同文件中的关键字写入不同的csv?在

非常感谢。在

def readwritevalue():
    for file in gettxtpath():    ##gettxtpath will return a list of files
        file1=file+".csv"
        ##Identify some variable
##Read the file
        with open(file) as fp:
            for line in fp:
                #Process the data
                data1=xxx
                data2=xxx
                ....
         ##Write it to different files
        with open(file1,"w") as fp1
            print(data1,file=fp1 )
            w = csv.writer(fp1)
            writer.writerow(data2)
            ...
if __name__ == '__main__':
    p = Process(target=readwritevalue)
    t1 = time.time()
    p.start()
    p.join()

想编辑我的问题。我有更多的函数来修改readwritevalue()函数生成的csv。 所以,如果池.map()很好。像这样改变所有剩下的功能可以吗?然而,这似乎并没有节省多少时间。在

^{pr2}$

Tags: 文件csvthe函数infor时间关键字
2条回答

我自己可能已经找到了答案。不太确定这是否是一个好的答案,但时间比以前缩短了6倍。在

def readwritevalue(file):
    with open(file, 'r', encoding='UTF-8') as fp:
        ##dataprocess
    file1=file+".csv"
    with open(file1,"w") as fp2:
        ##write data


if __name__=="__main__":
    pool=Pool(processes=int(mp.cpu_count()*0.7))
    pool.map(readwritevalue,[file for file in gettxtpath()])
    t1=time.time()
    pool.close()
    pool.join()

您可以将for循环的主体提取到它自己的函数中,创建a ^{} object,然后像这样调用^{}(我使用了更具描述性的名称):

import csv
import multiprocessing

def read_and_write_single_file(stem):
    data = None

    with open(stem, "r") as f:
        # populate data somehow

    csv_file = stem + ".csv"

    with open(csv_file, "w", encoding="utf-8") as f:
        w = csv.writer(f)

        for row in data:
            w.writerow(data)

if __name__ == "__main__":
    pool = multiprocessing.Pool()
    result = pool.map(read_and_write_single_file, get_list_of_files())

有关如何控制工人人数、每个工人的任务等,请参阅链接的文档

相关问题 更多 >