簡體   English   中英

無法格式化巨大的csv文件並通過python寫入文件

[英]Unable to format huge csv file and write to a file through python

我有300 MB的大型CSV文件。 如果有單列,我需要讀取文件並刪除該行; 如果第四列中有“ cloud”一詞,則將其追加。 所以我寫了一個腳本,該腳本首先讀取並將有效的數據寫入另一個csv。

首先,我寫了一個生成器來讀取數據,因為文件很大

def gen_csv(file_name):
  with open(file_name, 'rb') as csvfile:
   csvfile.seek(0)
   datareader =  csv.reader(csvfile, delimiter=',')
   for row in datareader:
     yield row

並調用writer函數

def format_csv(r_list):
  gzip_list = []
  for report in r_list:
    outputfile = report[:-4]+"-output.csv"
    with open(outputfile, 'wb') as firstcsv:
      firstcsv.seek(0)
      firstwriter = csv.writer(firstcsv, delimiter=',')
      for row in gen_csv(report):
        if len(row) == 1:
          continue
        elif row[3] == "Label":
          firstwriter.writerow(row)
        elif row[3].find('Cloud') > 0:
          firstwriter.writerow(row)
        else: pass

    firstcsv.close()

但是新CSV文件的第一個CSV的第一行只有一行。

提前致謝

編輯::

我發現我做的錯誤是選擇儀式行的邏輯錯誤。

您可以使用Pandas

代碼示例:

1-.
import pandas as pd
df = pd.read_csv("to_remove.csv")
keep_cols = ["Name", "Address"]
new_df = df[keep_cols]
new_df.to_csv("removed.csv", index=False) 


2.- 
df = pd.read_csv("your.csv", index_col=[0,1], skipinitialspace=True)
df.drop('column_name', axis=1, inplace=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM