【发布时间】:2018-09-21 22:57:52
【问题描述】:
我有一个包含 60 个文件夹的文件夹,每个文件夹包含大约 60 个 CSV(以及 1 个或 2 个非 CSV)。
我需要比较所有这些 CSV 的标题行,因此我试图通过目录并将输出 CSV (1) 相关文件的文件路径和 (2) 中的标题行写入输出 CSV 中行中的后续单元格。
然后转到下一个文件,在输出CSV的下一行写入相同的信息。
我在将标题行写入 CSV 的部分中迷失了——而且我迷失了,甚至无法生成错误消息。
谁能建议下一步该怎么做?
import os
import sys
import csv
csvfile = '/Users/username/Documents/output.csv'
def main(args):
# Open a CSV for writing outputs to
with open(csvfile, 'w') as out:
writer = csv.writer(out, lineterminator='\n')
# Walk through the directory specified in cmd line
for root, dirs, files in os.walk(args):
for item in files:
# Check if the item is a CSV
if item.endswith('.csv'):
# If yes, read the first row
with open(item, newline='') as f:
reader = csv.reader(f)
row1 = next(reader)
# Write the first cell as the file name
f.write(os.path.realpath(item))
f.write(f.readline())
f.write('\n')
# Write this row to a new line in the csvfile var
# Go to next file
# If not a CSV, go to next file
else:
continue
# Write each file to the CSV
# writer.writerow([item])
if __name__ == '__main__':
main(sys.argv[1])
【问题讨论】: