如何将多个 csv 文件整理成一个 csv 文件,每次删除 headers?
How to collate multiple csv files into one csv file, removing the headers each time?
我使用 python 从网上下载了大约 100 个 csv 文件。每个文件都是一年中的一个月,所以我实际上是在下载时间序列数据。
现在我想要的是将所有这些 csv 文件按时间顺序放入一个 csv 文件中,我不确定如何一个接一个地执行此操作?
我还要注意,除了第一次,我想在每次放入新的 csv 文件时删除 headers。
当您看到我的数据时,这将是有道理的:
感谢任何帮助,谢谢
按时间对您的 CSV 文件进行排序(大概这可以通过文件名的字母数字排序来完成),然后将所有文件连接在一起。这在 bash 中可能比在 python 中更容易做到,但这里有一个 python 解决方案(未经测试):
from glob import glob
# Fetch a sorted list of all .csv files
files = sorted(glob('*.csv'))
# Open output file for writing
with open('cat.csv', 'w') as fi_out:
# iterate over all csv files
for i, fname_in in enumerate(files):
# open each csv file
with open(fname_in, 'r') as fi_in:
# iterate through all files in the csv file
for i_line, line in enumerate(fi_in):
# Write all lines of the first file (i == 0)
# For all other files write all lines except the first one (i_line > 0)
if i_line > 0 or i == 0:
fi_out.write(line)
我使用 python 从网上下载了大约 100 个 csv 文件。每个文件都是一年中的一个月,所以我实际上是在下载时间序列数据。
现在我想要的是将所有这些 csv 文件按时间顺序放入一个 csv 文件中,我不确定如何一个接一个地执行此操作?
我还要注意,除了第一次,我想在每次放入新的 csv 文件时删除 headers。
当您看到我的数据时,这将是有道理的:
感谢任何帮助,谢谢
按时间对您的 CSV 文件进行排序(大概这可以通过文件名的字母数字排序来完成),然后将所有文件连接在一起。这在 bash 中可能比在 python 中更容易做到,但这里有一个 python 解决方案(未经测试):
from glob import glob
# Fetch a sorted list of all .csv files
files = sorted(glob('*.csv'))
# Open output file for writing
with open('cat.csv', 'w') as fi_out:
# iterate over all csv files
for i, fname_in in enumerate(files):
# open each csv file
with open(fname_in, 'r') as fi_in:
# iterate through all files in the csv file
for i_line, line in enumerate(fi_in):
# Write all lines of the first file (i == 0)
# For all other files write all lines except the first one (i_line > 0)
if i_line > 0 or i == 0:
fi_out.write(line)