python - Python:如何将列表压缩为 zip 文件
问题描述
请帮忙,因为我是python新手..
我正在尝试根据匹配项获取列表并将它们写入单独的压缩 gz 文件,根据 gzip 模块文档。但我得到了TypeError: memoryview: a bytes-like object is required, not 'str'
。不知道我在这里犯了什么错误。
Python code
import re
from collections import defaultdict
import gzip
X = ['apple,banana,fruits,orange', 'dog,cat,animals,horse', 'mouse,elephant,animals,peacock']
filter = ('fruits', 'animals')
d = defaultdict(list)
for x in X:
for f in filter:
if re.search(fr'\b{f}\b', x):
d[f].append(x)
for k, v in d.items():
with gzip.open(f'{k}.csv.gz', 'wb') as fi:
for y in v:
fi.write(y)
从 X 中的列表中,它匹配filter
(水果、动物)并写入单独的 csv 文件,如果将 gzip.open 替换为刚刚打开。但我想以压缩的 gz 格式编写它们,并使用 gzip 文档中的上述示例。
with open(f'{k}.csv', 'w') as fi: #It works fine for writing into csv file. (thanks to Austin)
with gzip.open(f'{k}.csv.gz', 'wb') as fi: # Gives below error.
错误:
Traceback (most recent call last):
File "c:\Users\Maria\Documents\drs\stopper.py", line 17, in <module>
fi.write(y)
File "C:\Users\Maria\anaconda3\lib\gzip.py", line 260, in write
data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'
Expected Output:
zcat fruits.csv.gz
apple,banana,fruits,orange
zcat animals.csv.gz
mouse,elephant,animals,peacock
mouse,elephant,animals,peacock
请帮助..提前谢谢。
解决方案
推荐阅读
- java - 小心使用方法的警告
- javascript - jest.doMock 和 JSON 导入模拟
- java - 将其认知复杂度从 59 降低到允许的 15
- maven - Quarkus:maven部署runner jar
- android - Android Firefox-debug per USB, Inspector 什么也没显示
- c# - C# Entity Framework MySQL 使用 SRID 4326 注册空间数据
- angular - 我们如何根据角度反应形式的数据库中的值将动态复选框设置为检查?
- angular - 如何电子 main.ts 调用或发送消息到角度组件
- android - 在同一个对话框中同时询问多个权限
- typo3 - TYPO3:使用 TYPO3 Querybuilder 在 OrderBy 中使用 IS NULL 和 COALESCE