簡體   English   中英

python gzipped fileinput返回二進制字符串而不是文本字符串

[英]python gzipped fileinput returns binary string instead of text string

當我使用模塊 fileinput 遍歷一組 gzipped 文件的行時,如下所示:

for line in fileinput.FileInput(files=gzipped_files,openhook=fileinput.hook_compressed):

那么這些行是字節字符串而不是文本字符串。

使用模塊 gzip 時,可以通過使用“rt”而不是“rb”打開文件來防止這種情況: http : //bugs.python.org/issue13989

模塊文件輸入是否有類似的修復,所以我可以讓它返回文本字符串而不是字節字符串? 我嘗試添加 mode='rt',但隨后出現此錯誤:

ValueError: FileInput opening mode must be one of 'r', 'rU', 'U' and 'rb'

您必須實現自己的openhook函數才能使用編解碼器打開文件:

import os

def hook_compressed_text(filename, mode, encoding='utf8'):
    ext = os.path.splitext(filename)[1]
    if ext == '.gz':
        import gzip
        return gzip.open(filename, mode + 't', encoding=encoding)
    elif ext == '.bz2':
        import bz2
        return bz2.open(filename, mode + 't', encoding=encoding)
    else:
        return open(filename, mode, encoding=encoding)

參加聚會有點晚了,但這樣做不是更簡單嗎?

for line in fileinput.FileInput(files=gzipped_files, openhook=fileinput.hook_compressed):
    if isinstance(line, bytes):
        line = line.decode()
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM