2017-10-10 201 views
1

我有一個csv文件有500萬行。 我想將文件拆分成由用戶指定的行數。通過python分割一個大的csv文件

已開發了以下代碼,但其執行時間太長。任何人都可以幫助我優化代碼。

import csv 
print "Please delete the previous created files. If any." 

filepath = raw_input("Enter the File path: ") 

line_count = 0 
filenum = 1 
try: 
    in_file = raw_input("Enter Input File name: ") 
    if in_file[-4:] == ".csv": 
     split_size = int(raw_input("Enter size: ")) 
     print "Split Size ---", split_size 
     print in_file, " will split into", split_size, "rows per file named as OutPut-file_*.csv (* = 1,2,3 and so on)" 
     with open (in_file,'r') as file1: 
      row_count = 0 
      reader = csv.reader(file1) 
      for line in file1: 
       #print line 
      with open(filepath + "\\OutPut-file_" +str(filenum) + ".csv", "a") as out_file: 
       if row_count < split_size: 
        out_file.write(line) 
        row_count = row_count +1 
       else: 
        filenum = filenum + 1 
        row_count = 0 
      line_count = line_count+1 
     print "Total Files Written --", filenum 
    else: 
     print "Please enter the Name of the file correctly."   
except IOError as e: 
    print "Oops..! Please Enter correct file path values", e 
except ValueError: 
    print "Oops..! Please Enter correct values" 

我自己也嘗試沒有 「打開」

+5

來些更傳統的單位超過萬盧比?;) – liborm

+0

關於與不同的文件指針尋求不同點,並使用所有這些通過並行協同例程/ GEVENT什麼? – SRC

+0

我還沒有嘗試過..你可以請幫助相同。多線程或多任務在這裏會有幫助。 – user2597209

回答

2

Oups!您一再重新打開輸出文件的每一行,當它是一個昂貴的操作...你的代碼可能會變成:

... 
    with open (in_file,'r') as file1: 
     row_count = 0 
     #reader = csv.reader(file1) # unused here 
     out_file = open(filepath + "\\OutPut-file_" +str(filenum) + ".csv", "a") 
     for line in file1: 
      #print line 
      if row_count >= split_size: 
       out_file.close() 
       filenum = filenum + 1 
       out_file = open(filepath + "\\OutPut-file_" +str(filenum) + ".csv", "a") 
       row_count = 0 
      out_file.write(line) 
      row_count = row_count +1 
      line_count = line_count+1 
     ... 

理想情況下,你甚至應該在try塊之前初始化out_file = None,確保乾淨if out_file is not None: out_file.close()

備註:此代碼僅在行數中分開(與您的一樣)。這意味着如果csv文件可以在引用字段中包含換行符,那麼將會給出錯誤的輸出...

+0

哦..在這種情況下..我需要檢查新的線。對? – user2597209

+0

@ user2597209:如果你想允許帶引號的字段換行,你將不得不解析使用CSV閱讀器的輸入文件,並用CSV作家寫的行,或做手工解析,但它是複雜與許多其他的情況。 –

0

您絕對可以使用python的多處理模塊。

這是我獲得的結果,當我有一個csv文件,其中有1,000,000行。

import time 
from multiprocessing import Pool 

def saving_csv_normally(start): 
    out_file = open('out_normally/' + str(start/batch_size) + '.csv', 'w') 
    for i in range(start, start+batch_size): 
    out_file.write(arr[i]) 
    out_file.close() 

def saving_csv_multi(start): 
    out_file = open('out_multi/' + str(start/batch_size) + '.csv', 'w') 
    for i in range(start, start+batch_size): 
    out_file.write(arr[i]) 
    out_file.close() 

def saving_csv_multi_async(start): 
    out_file = open('out_multi_async/' + str(start/batch_size) + '.csv', 'w') 
    for i in range(start, start+batch_size): 
    out_file.write(arr[i]) 
    out_file.close() 

with open('files/test.csv') as file: 
    arr = file.readlines() 

print "length of file : ", len(arr) 

batch_size = 100 #split in number of rows 

start = time.time() 
for i in range(0, len(arr), batch_size): 
    saving_csv_normally(i) 
print "time taken normally : ", time.time()-start 

#multiprocessing 
p = Pool() 
start = time.time() 
p.map(saving_csv_multi, range(0, len(arr), batch_size), chunksize=len(arr)/4) #chunksize you can define as much as you want 
print "time taken for multiprocessing : ", time.time()-start 

# it does the same thing aynchronically 
start = time.time() 
for i in p.imap_unordered(saving_csv_multi_async, range(0, len(arr), batch_size), chunksize=len(arr)/4): 
    continue 
print "time taken for multiprocessing async : ", time.time()-start 

輸出顯示每個所用的時間:

length of file : 1000000 
time taken normally : 0.733881950378 
time taken for multiprocessing : 0.508712053299 
time taken for multiprocessing async : 0.471592903137 

我已經定義三個單獨用作在p.map傳遞只能有一個參數的功能和作爲我存儲在三個不同的文件夾的CSV文件這就是爲什麼我寫了三個函數。