在Python 3.6中提取没有BOM的gzip文件



我在子文件夹中有多个gzfile,我想在一个文件夹中解压缩。它工作正常,但每个文件的开头都有一个 BOM 签名,我想删除它。我已经检查了其他问题,例如从 Python 中的 gzip CSV 中删除 BOM 或将带有 BOM 的 UTF-8 转换为 Python 中没有 BOM 的 UTF-8,但它似乎不起作用。我在Windows上的Pycharm中使用Python 3.6。

这是第一个我的代码,没有尝试:

import gzip
import pickle
import glob

def save_object(obj, filename):
    with open(filename, 'wb') as output:  # Overwrites any existing file.
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

output_path = 'path_out'
i = 1
for filename in glob.iglob(
        'path_in/**/*.gz', recursive=True):
    print(filename)
    with gzip.open(filename, 'rb') as f:
        file_content = f.read()
    new_file = output_path + "z" + str(i) + ".txt"
    save_object(file_content, new_file)
    f.close()
    i += 1

现在,使用在 Python 中从 gzip 的 CSV 中删除 BOM 中定义的逻辑(至少我对此的理解(,如果我将 file_content = f.read() 替换为 file_content = csv.reader(f.read().decode('utf-8-sig').encode('utf-8').splitlines()) ,我会得到:

类型错误:无法腌制_csv.reader 对象

我检查了此错误(例如,在Windows上使用多处理时"无法腌制<键入'_csv.reader'>"错误(,但我找不到可以应用的解决方案。

对你链接到的第一个问题的小改编工作。

tripleee$ cat bomgz.py
import gzip
from subprocess import run
with open('bom.txt', 'w') as handle:
    handle.write('ufeffmoo!n')
run(['gzip', 'bom.txt'])
with gzip.open('bom.txt.gz', 'rb') as f:
    file_content = f.read().decode('utf-8-sig')
with open('nobom.txt', 'w') as output:
    output.write(file_content)
tripleee$ python3 bomgz.py
tripleee$ gzip -dc bom.txt.gz | xxd
00000000: efbb bf6d 6f6f 210a                      ...moo!.
tripleee$ xxd nobom.txt
00000000: 6d6f 6f21 0a                             moo!.

pickle部分在这里似乎无关紧要,但可能掩盖了从编码的bytes块中获取解码str块的目标。

最新更新