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

时间:2017-01-03 10:02:34

标签: python csv

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

示例

输入csv文件1 (test1.csv)

Id, ProductName
1, ABC

输入csv文件2 (test2.csv)

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

OUTPUTFILE

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)

非常感谢你的帮助。

更新: 此代码可以正常用于此目的:

private var currentBackForwardItem: WKBackForwardListItem?
private func handleBackForwardWebView(navigationAction: WKNavigationAction) {
    if navigationAction.navigationType == .BackForward {
        let isBack = webView.backForwardList.backList
            .filter { $0 == currentBackForwardItem }
            .count == 0

        if isBack {

        } else {

        }
    }

    currentBackForwardItem = webView.backForwardList.currentItem
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    handleBackForwardWebView(navigationAction)
    decisionHandler(.Allow)
}

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

一种简单的方法是在文件对象上使用readline()

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

答案 2 :(得分:0)

使用csv模块清理解决方案,以阅读撰写

  • 打开输出文件并在其句柄上创建csv.writer实例
  • 打开每个输入文件并在其句柄上创建csv.reader实例
  • 使用next迭代器上的csv.reader获取第一行:获取标题作为列表(使用小的后处理来删除空格)
  • 在循环中将当前文件名旁边的标题写入

代码:

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模块有几个优点,最重要的是引用&多行字段/标题管理得当。