1. 程式人生 > 實用技巧 >統計某資料夾下的所有csv檔案的行數(多程序)

統計某資料夾下的所有csv檔案的行數(多程序)

統計某資料夾下的所有csv檔案的行數(多程序),程式碼如下

#-*- coding: utf-8 -*-
# 統計某資料夾下的所有csv檔案的行數(多程序)
import os
import multiprocessing
import csv


def getline(path, mylist):
    reader = csv.reader(open(path, "r"))  # 讀取檔案
    lines = 0
    for item in reader:  # 讀取每一行
        lines += 1
    print("self pid", os.getpid(), "
lines", lines) mylist.append(lines) # 將csv檔案的行數新增到行數列表 if __name__ == "__main__": path = "/home/test4" # 存放所有csv檔案的資料夾 filelist = os.listdir(path) # 儲存了所有的檔名 processlist = [] # 程序列表 mylist = multiprocessing.Manager().list() # 多程序共享list,共享記憶體。存放所有csv檔案的行數的List for filename in
filelist: newpath = path + "/" + filename # 絕對路徑 p = multiprocessing.Process(target=getline, args=(newpath, mylist)) # 開啟程序 p.start() # 程序開始幹活 processlist.append(p) # 加入程序列表 for mythd in processlist: # 遍歷每一個程序 mythd.join() # 等待所有程序幹完活 print(mylist) total
= 0 #統計行數列表總和 total = sum(mylist) print(total) print("完成")