2017-01-03 97 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

感谢您的帮助。 –