【问题标题】:Python - Crawling Directory, Extracting CSV Files from ZIPs, and Combining Multiple CSVsPython - 爬取目录、从 ZIP 中提取 CSV 文件以及组合多个 CSV
【发布时间】:2020-09-11 02:14:59
【问题描述】:

我有一个使用 pandas 组合多个 ZIP 文件的 Python 脚本。我正在使用托管在 GitHub 存储库中的奥地利 COVID-19 病例数据:https://github.com/statistikat/coronaDAT

我试图让它在 GitHub 存储库中抓取目录结构(所有文件夹和子文件夹),识别 ZIP 文件,然后从 ZIP 文件中提取特定的 CSV 文件并组合 CSV。在这种情况下,将所有标题为“Bezirke.csv”的 CSV 文件合并为一个。

我有一个在当前工作文件夹中执行此操作的脚本的工作版本,但不会抓取目录结构或进入子文件夹。请参阅this 问题。

我现在正在尝试使用os.walk(rootPath) 来抓取结构。它似乎正在工作,但停止并显示错误消息:

Traceback (most recent call last):
  File "merge_zip_entire_directory.py", line 21, in <module>
    zip_file = ZipFile(filename)
  File "/Users/matt/opt/anaconda3/lib/python3.7/zipfile.py", line 1240, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: '20200422_060000_orig_csv.zip'

我已验证该特定 zip 文件有一个名为“Bezirke.csv”的文件。我不明白为什么我会收到错误消息。

这是完整的脚本:

import fnmatch
import os
import pandas as pd
from zipfile import ZipFile


#set root path
rootPath = r"/Users/matt/OneDrive/Documents/04 Employment/Employers/State Department/COVID-19/test/"

#set file pattern
pattern = '*.zip'

#initialize variables
df_master = pd.DataFrame()
flag = False


#crawl entire directory in root folder
for root, dirs, files in os.walk(rootPath):
    #filter files that match pattern of .zip
    for filename in fnmatch.filter(files, pattern):
        #
        zip_file = ZipFile(os.path.join(root, filename))
        for text_file in zip_file.infolist():
            if text_file.filename.endswith('Bezirke.csv'):
                df = pd.read_csv(zip_file.open(text_file.filename), 
                delimiter=';', 
                header=0, 
                index_col=['Timestamp'], 
                parse_dates=['Timestamp']
                )
            if not flag:
                df_master = df
                flag = True
            else:
                df_master = pd.concat([df_master, df])

#sort index field Timestamp
df_master.sort_index(inplace=True)

#print master dataframe info
print(df_master.info())

#prepare date to export to csv
frame = df_master

#export to csv
try:
    frame.to_csv( "combined_zip_Bezirke.csv", encoding='utf-8-sig')
    print("Export to CSV Successful")
except:
    print("Export to CSV Failed")

【问题讨论】:

    标签: python pandas csv zipfile


    【解决方案1】:

    您忘记包含路径 - os.walk 返回的文件名只是文件名,没有指向该文件名的路径。你需要的是:

    zip_file = ZipFile(os.path.join(root, filename))
    

    另外,你在 for 循环中的缩进是错误的,一定是:

    for text_file in zip_file.infolist():
        if text_file.filename.endswith('Bezirke.csv'):
            df = pd.read_csv(zip_file.open(text_file.filename),
                delimiter=';',
                header=0,
                index_col=['Timestamp'],
                parse_dates=['Timestamp']
                )
            if not flag:
                df_master = df
                flag = True
            else:
                df_master = pd.concat([df_master, df])
    

    【讨论】:

    • 我按照建议调整了代码。但收到消息:Traceback (most recent call last): File "merge_zip_entire_directory.py", line 33, in &lt;module&gt; df_master = df NameError: name 'df' is not defined。 - 我需要在 for 语句之外定义 df 变量吗?
    • 不,你只需要正确缩进 if/else 块,看我更新的答案
    猜你喜欢
    • 1970-01-01
    • 2021-09-22
    • 2021-01-21
    • 1970-01-01
    • 2020-10-05
    • 2012-03-09
    • 1970-01-01
    • 2016-01-06
    • 2018-12-21
    相关资源
    最近更新 更多