Python读取CSV文件列并在CSV-fi中写入文件名和列名

2024-09-30 00:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多CSV文件,需要读取循环中的所有文件,并在输出文件中写入文件名和所有列(第一行的标题)。在

示例

输入csv文件1(test1.csv)

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

输入csv文件2(test2.csv)

^{pr2}$

输出文件

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

非常感谢你的帮助。在

更新: 本规范适用于以下目的:

import os
import csv

ofile = open('D:\Anuj\Personal\OutputFile/AHS_File_Columns_Info.csv', 'w')

directory = os.path.join('D:\Anuj\Personal\Python')

for root, dirs, files in os.walk(directory):
    for file in files:
            fullfilepath = directory + "/" + file
            with open(fullfilepath,'r') as f:
                output = file +','+ f.readline()
                ofile.write(output)

Tags: 文件csvnameimportidageoslocation
3条回答

使用csv模块清洗溶液,用于读取写入

  • 打开输出文件并在其句柄上创建一个csv.writer实例
  • 打开每个输入文件并在其句柄上创建一个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模块有几个优点,最重要的是引用和多行字段/标题得到了正确的管理。在

但我不确定我是否理解你的意思。在

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)

一个简单的方法是在file对象上使用readline()

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

相关问题 更多 >

    热门问题