我有很多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)
使用
csv
模块清洗溶液,用于读取和写入csv.writer
实例csv.reader
实例csv.reader
迭代器上使用next
获取第一行:以列表形式获取标题(通过一个小的后处理删除空格)代码:
使用
csv
模块有几个优点,最重要的是引用和多行字段/标题得到了正确的管理。在但我不确定我是否理解你的意思。在
一个简单的方法是在file对象上使用
readline()
:相关问题 更多 >
编程相关推荐