gpt4 book ai didi

python - 多处理列表中的多个文件

转载 作者:太空狗 更新时间:2023-10-30 02:31:05 24 4
gpt4 key购买 nike

我正在尝试读取一个列表,其中包含同步存储在列表中的 N 个 .csv 文件。

现在我做了以下事情:

导入多进程

  1. 空列表
  2. 用 .csv 的 listdir 附加列表
  3. def A() -- 偶数文件 (list[::2])
  4. def B() -- 奇数文件(列表[1::2]
  5. 处理 1 def A()
  6. 进程 2 def B()

    def read_all_lead_files(folder):

    for files in glob.glob(folder+"*.csv"):
    file_list.append(files)
    def read_even():
    file_list[::2]
    def read_odd():
    file_list[1::2]

    p1 = Process(target=read_even)
    p1.start()
    p2 = Process(target=read_odd)
    p2.start()

是否有更快的方法将列表的分区拆分为 Process 函数?

最佳答案

我是应您的要求猜测的,因为原始问题还不清楚。由于 os.listdir 不保证顺序,我假设你的“两个”功能实际上是相同的,你只需要同时对多个文件执行相同的过程。

根据我的经验,最简单的方法是启动一个 Pool,为每个文件启动一个进程,然后等待。例如

import multiprocessing

def process(file):
pass # do stuff to a file

p = multiprocessing.Pool()
for f in glob.glob(folder+"*.csv"):
# launch a process for each file (ish).
# The result will be approximately one process per CPU core available.
p.apply_async(process, [f])

p.close()
p.join() # Wait for all child processes to close.

关于python - 多处理列表中的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23794207/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com