【发布时间】:2019-03-04 06:40:53
【问题描述】:
在合并多个 CSV 文件时,我可以从所有文件中获取标题,也可以根本不获取任何标题。我只想要第一个文件的标题,因为所有文件都有相同的标题,我正在合并列下方的列。
我是python的新手。实际上在不同的子文件夹中有 23 个同名的 CSV 文件。我正在使用循环逐行读取它们。我只想要第一个文件头。
这是我的代码:
import os, sys
`import pathlib
# Specify directory
# In your case, you may want something like the following
my_directory = 'C:/Users/Arijeet/Downloads'
file = pathlib.Path("out.csv")
if file.exists ():
print("file found\nremoving")
os.remove('out.csv')
else:
print("file not find\ncreating")
counter = 1
# Start the loop
for folder, sub_folders, files in os.walk(my_directory):
for special_file in files:
if special_file == 'iono_tropo.csv':
file_path = os.path.join(folder, special_file)
# Open and read
with open(file_path) as read_file:
print('Reading iono_tropo csv file ' + str(counter))
lines=read_file.readlines()
with open ("out.csv","a+") as f:
f.writelines(lines)
counter += 1
我能做什么?
【问题讨论】:
-
我建议使用 pandas 来做到这一点。 pandas.pydata.org
标签: python python-3.x csv merge header