python - 如何在压缩文件中的文件夹中打开多个 csv 文件
问题描述
压缩文件 --> 10 个文件夹 --> 每个文件夹 20 个 csv 文件
- 压缩文件的标题是 yyyy-mm
- 文件夹标题是 yyyy-mm-dd
- 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()
解决方案
如果不需要处理压缩文件,您可以先解压缩它们:
import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
zip_ref.extractall(directory_to_extract_to)
然后正常使用提取的文件夹。
推荐阅读
- node.js - Next.js, Next/Image 从本地运行的后端服务器获取图像
- java - 不兼容的类型。找到 java.lang.Class
>, 需要 char,byte,short,int - android - 使用 EncryptedSharedPreferences 时获取 java.lang.ClassCastException
- javascript - React、Apollo、Shopify Polaris:出现 TypeError:rows.map 不是函数。(在 'rows.map(this.defaultRenderRow)' 中,'rows.map' 未定义)
- android - Google Play 结算:未完成的购买不可用于订阅?
- php - 如何在 Blade 上检查会话值
- amazon-web-services - 如何在 zsh 中设置 s3 复制命令
- apache-kafka - Kafka 多个消费者组不同的线程未按预期工作
- python - Python 将字典值映射到 XML 文件
- python - 代码仅返回 if 语句,忽略其他所有内容