[英]Extract gzip file without BOM in Python 3.6
我在子文件夾中有多個 gzfile,我想將它們解壓縮到一個文件夾中。 它工作正常,但在我想刪除的每個文件的開頭都有一個 BOM 簽名。 我已經檢查了其他問題,例如從 Python 中的 gzip'ed CSV 中刪除 BOM或將帶有 BOM 的 UTF-8 轉換為 UTF-8,但在 Python 中沒有 BOM,但它似乎不起作用。 我在 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 上使用多處理時“Can't pickle <type '_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
塊的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.