簡體   English   中英

將過濾后的CSV文件寫入新文件並遍歷文件夾

[英]Writing a filtered CSV file to a new file and iterating through a folder

我最初一直在嘗試創建一個程序來遍歷一個文件並選擇某些列,然后將其移至新的文本文件。 到目前為止,我有

    import os, sys, csv
    os.chdir("C://Users//nelsonj//Desktop//Master_Project")
    with open('CHS_2009_test.txt', "rb") as sitefile:
    reader = csv.reader(sitefile, delimiter=',')
    pref_cols = [0,1,2,4,6,8,10,12,14,18,20,22,24,26,30,34,36,40]

    for row in reader:
        new_cols = list(row[i] for i in pref_cols)
        print new_cols

我一直在嘗試使用csv函數編寫新文件,但是我一直在出錯。 我最終將需要在一個文件文件夾中執行此操作,但是我想在解決該問題之前會嘗試在一個文件上執行此操作。

我試圖用來將數據寫入新文件的代碼

    for row in reader:
        with open("CHS_2009_edit.txt", 'w') as file:
            new_cols = list(row[i] for i in pref_cols)
            newfile = csv.writer(file)
            newfile.writerows(new_cols)

這種工作方式是,我得到一個新文件,但只從csv打印第二行值,即不打印標題值,並在每個單獨的字符之間放置逗號,而不僅僅是復制原始列。

我正在將PythonWin與Python 2.6(來自ArcGIS)一起使用

謝謝您的幫助!

新的更新代碼

   import os, sys, csv

   path = ('C://Users//nelsonj//Desktop//Master_Project')

   for filename in os.listdir(path):

       pref_cols = [0,1,2,4,6,8,10,12,14,18,20,22,24,26,30,34,36,40]
       with open(filename, "rb") as sitefile:
           with open(filename.rsplit('.',1)[0] + "_Master.txt", 'w') as output_file:
               reader = csv.reader(sitefile, delimiter=',')
               writer = csv.writer(output_file)
               for row in reader:
                   new_row = list(row[i] for i in pref_cols)
                   writer.writerow(new_row)
                   print new_row

正在使列表索引超出new_row的范圍,但似乎仍在處理文件。 我現在無法做的唯一事情就是遍歷目錄中的所有文件。 是數據文本文件的屏幕快照的超鏈接

嘗試這個:

 new_header = list(row[i] for i in pref_cols if i in row)

那應該避免該錯誤,但是可能不能避免潛在的問題。 您可以將CSV文件粘貼到我可以訪問的位置,然后為您修復該文件嗎?

出於過濾的目的,您不必將標頭與其余數據區別對待。 您可以繼續刪除以下代碼塊:

    headers = reader.next()
    for row in headers:
        new_header = list(row[i] for i in pref_cols)
        print new_header  

您的代碼無法正常工作,因為您將標題視為行列表,但是標題僅是一行。

更新

此更新處理將CSV數據寫入新文件。 您應該將open語句移至for row...上方for row...

with open("CHS_2009_edit.txt", 'w') as output_file:
    writer = csv.writer(output_file)
    for row in reader:
        new_cols = list(row[i] for i in pref_cols)
        writer.writerows(new_cols)

更新2

此更新處理標題輸出問題。 如果您遵循我的建議,則應該不會出現此問題。 我不知道您當前的代碼是什么樣子,但是看起來您在代碼需要列表的地方提供了一個字符串。 這是我在系統上嘗試過的代碼(使用制成的數據),它似乎可以正常工作:

pref_cols = [...] # <<=== Should be set before entering the loop
with open('CHS_2009_test.txt', "rb") as sitefile:
    with open('CHS_2009_edit.txt', 'w') as output_file:
        reader = csv.reader(sitefile, delimiter=',')
        writer = csv.writer(output_file)
        for row in reader:
            new_row = list(row[i] for i in pref_cols)
            writer.writerow(new_row)

需要注意的一件事:我使用writerow()來寫一行,在這里您使用writerows() -會writerows()

暫無
暫無

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

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