首页 > 解决方案 > 如何在压缩文件中的文件夹中打开多个 csv 文件

问题描述

压缩文件 --> 10 个文件夹 --> 每个文件夹 20 个 csv 文件

尝试了以下代码但不起作用

import pandas as pd
import os
import glob
     
myzip=zipfile.ZipFile("C:/xxx/xxx/xxx/xxx/2021-01.zip")
for fname in myzip.namelist():
    if 'csv' not in fname:
        pathname = "C:/xxx/xxx/xxx/xxx/2021-01.zip/" + fname
        path = os.getcwd()
        csv_files = glob.glob(os.path.join(pathname, "*.csv"))  
     
        for f in csv_files:
            # read the csv file
            df = pd.read_csv(f)

            # print the location and filename
            print('Location:', f)
            print('File Name:', f.split("\\")[-1])

            # print the content
            print('Content:')
            display(df)
            print()

标签: python

解决方案


如果不需要处理压缩文件,您可以先解压缩它们:

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

然后正常使用提取的文件夹。


推荐阅读