首页 > 解决方案 > 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

请帮助..提前谢谢。

标签: pythonpython-3.xlistgzip

解决方案


推荐阅读