2017-01-03 99 views
0

我有許多CSV文件,需要讀取循環中的所有文件並寫入文件名以及輸出中的所有列(行1中的標題)文件。Python讀取CSV文件列並在csv文件中寫入文件名和列名

輸入csv文件1(test1.csv)

Id, Name, Age, Location 
1, A, 25, India 

輸入csv文件2(test2.csv)

Id, ProductName 
1, ABC 

OUTPUTFILE

test1.csv Id 
test1.csv Name 
test1.csv Age 
test1.csv Location 
test2.csv Id 
test2.csv ProductName 

非常感謝您的幫助。

更新: 此代碼工作正常爲此目的:

​​
+0

你應該重新格式化你的代碼。 –

+0

這應該會給你你需要的幫助。 https://stackoverflow.com/questions/3428532/how-to-import-a-csv-file-using-python-with-headers-intact-where-first-column-is – fuuman

回答

0
使用 csv模塊用於讀取 寫入

  • 打開的輸出文件和

    清潔溶液創建csv.writer其手柄上的實例

  • open每個輸入文件,並在他們的手柄創建csv.reader實例
  • 坐上csv.reader迭代器使用next第一行:獲得冠軍的列表(用小處理後把空格去掉)
  • 寫標題當前文件名在旁邊循環

代碼:

import csv 

files=["test1.csv","test2.csv"] 
with open("output.tsv","w",newline='') as fw: 
    cw = csv.writer(fw,delimiter="\t") # output is tab delimited 
    for filename in files: 
     with open(filename,'r') as f: 
      cr = csv.reader(f) 
      # get title 
      for column_name in (x.strip() for x in next(cr)): 
       cw.writerow([filename,column_name]) 

有使用csv模塊,最重要的一點就是引用幾個優點多行字段/標題管理得當。

+0

非常感謝。我得到這個錯誤:AttributeError:'模塊'對象沒有'作家'屬性 –

+0

我想你叫你的模塊'csv.py'。重命名它。 –

0

但我不知道我理解正確。

import csv 
from typing import List 
from typing import Tuple 

TableType = List[List[str]] 


def load_csv_table(file_name: str) -> Tuple[List[str], TableType]: 
    with open(file_name) as csv_file: 
     csv_reader = csv.reader(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) 
     headers = next(csv_reader) 
     data_table = list(csv_reader) 
     return headers, data_table 


def save_csv_table(file_name: str, headers: List[str], data_table: TableType): 
    with open(file_name, 'w', newline='') as csv_file: 
     writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) 
     writer.writerow(headers) 
     for row in data_table: 
      writer.writerow(row) 


input_files = ['file1.csv', 'file2.csv', 'file3.csv'] 
new_table = [] 
new_headers = [] 
for file_name in input_files: 
    headers, data_table = load_csv_table(file_name) 
    if not new_headers: 
     new_headers = ['Source'] + headers 
    new_table.extend(([file_name] + line for line in data_table)) 
save_csv_table('output.csv', new_headers, new_table) 
+0

非常感謝。此代碼工作正常,我:進口OS 導入CSV OFILE =開放( 'd:\ Anuj \個人\ OUTPUTFILE/AHS_File_Columns_Info.csv', 'W') 目錄= os.path.join('d: \ Anuj \ Personal \ Python') for root,dirs,os in。對於文件中的文件: : fullfilepath = directory +「/」+文件 與開放.write(輸出) –

0

一個簡單的方法是將文件對象上使用readline()

files=["test1.csv","test2.csv"] 
for my_file in files: 
    with open(my_file,'r') as f: 
     print my_file, f.readline() 
+0

感謝您的幫助。 –