从多个zip文件合并csvs python

问题描述 投票:0回答:1

我有一个包含许多 zip 文件的文件夹。每个 zip 文件适用于一年中的一个月。每个 zip 文件包含该月每一天的多个 csv。所有 zip 文件中的所有 csv 的标题都是相同的。

我想编写一个 python 脚本,使用 pandas 将文件夹中所有 zip 文件中的所有 csv 合并到一个巨大的 csv 文件中。

zip 文件名称约定 = yyyymmdddamasp_csv.zip

单独的 csv 文件命名约定= yyyymmdddamasp.csv

我是Python的初学者**。我正在尝试这个潜在的解决方案,但我不确定。

import os
import pandas as pd
import zipfile

# Path to the folder containing the zip files
folder_path = "path_to_folder_containing_zip_files"

# Initialize an empty list to store DataFrame for each CSV
dfs = []

# Iterate through each zip file in the folder
for file_name in os.listdir(folder_path):
if file_name.endswith('.zip'):
# Open the zip file
with zipfile.ZipFile(os.path.join(folder_path, file_name), 'r') as zip_ref:
# Iterate through each CSV file in the zip file
for csv_file_name in zip_ref.namelist():
if csv_file_name.endswith('.csv'):
# Read the CSV file into a DataFrame
with zip_ref.open(csv_file_name) as csv_file:
df = pd.read_csv(csv_file)
# Append the DataFrame to the list
dfs.append(df)

# Concatenate all DataFrames in the list into a single DataFrame
combined_df = pd.concat(dfs, ignore_index=True)

# Save the combined DataFrame to a CSV file
combined_df.to_csv('combined_data.csv', index=False)
python pandas csv zip
1个回答
0
投票

您的代码似乎是正确的,因为上面的注释表明您必须为每行代码设置缩进。

© www.soinside.com 2019 - 2024. All rights reserved.