![](/img/trans.png)
[英]Python: How can I read a line from a compressed 7z file in Python?
[英]How to read from a text file compressed with 7z?
我想從 7z 壓縮的 csv(文本)文件中逐行讀取(在 Python 2.7 中)。 我不想解壓縮整個(大)文件,而是要流式傳輸這些行。
我嘗試pylzma.decompressobj()
失敗。 我收到數據錯誤。 請注意,此代碼尚未逐行讀取:
input_filename = r"testing.csv.7z"
with open(input_filename, 'rb') as infile:
obj = pylzma.decompressobj()
o = open('decompressed.raw', 'wb')
obj = pylzma.decompressobj()
while True:
tmp = infile.read(1)
if not tmp: break
o.write(obj.decompress(tmp))
o.close()
輸出:
o.write(obj.decompress(tmp))
ValueError: data error during decompression
這將允許您迭代這些行。 它部分源自我在另一個問題的答案中找到的一些代碼。
此時 ( pylzma-0.5.0
) py7zlib
模塊沒有實現允許將存檔成員作為字節或字符流讀取的py7zlib
它的ArchiveFile
類只提供了一個read()
函數,用於解壓縮和一次性返回成員中未壓縮的數據。 鑒於此,可以做的最好的事情是通過 Python 生成器將其用作緩沖區,以迭代方式返回字節或行。
以下是后者,但如果問題是存檔成員文件本身很大,則可能無濟於事。
下面的代碼應該適用於 Python 3.x 和 2.7。
import io
import os
import py7zlib
class SevenZFileError(py7zlib.ArchiveError):
pass
class SevenZFile(object):
@classmethod
def is_7zfile(cls, filepath):
""" Determine if filepath points to a valid 7z archive. """
is7z = False
fp = None
try:
fp = open(filepath, 'rb')
archive = py7zlib.Archive7z(fp)
_ = len(archive.getnames())
is7z = True
finally:
if fp: fp.close()
return is7z
def __init__(self, filepath):
fp = open(filepath, 'rb')
self.filepath = filepath
self.archive = py7zlib.Archive7z(fp)
def __contains__(self, name):
return name in self.archive.getnames()
def readlines(self, name, newline=''):
r""" Iterator of lines from named archive member.
`newline` controls how line endings are handled.
It can be None, '', '\n', '\r', and '\r\n' and works the same way as it does
in StringIO. Note however that the default value is different and is to enable
universal newlines mode, but line endings are returned untranslated.
"""
archivefile = self.archive.getmember(name)
if not archivefile:
raise SevenZFileError('archive member %r not found in %r' %
(name, self.filepath))
# Decompress entire member and return its contents iteratively.
data = archivefile.read().decode()
for line in io.StringIO(data, newline=newline):
yield line
if __name__ == '__main__':
import csv
if SevenZFile.is_7zfile('testing.csv.7z'):
sevenZfile = SevenZFile('testing.csv.7z')
if 'testing.csv' not in sevenZfile:
print('testing.csv is not a member of testing.csv.7z')
else:
reader = csv.reader(sevenZfile.readlines('testing.csv'))
for row in reader:
print(', '.join(row))
如果您可以使用 python 3,則有一個有用的庫py7zr ,它支持部分7zip 解壓,如下所示:
import py7zr
import re
filter_pattern = re.compile(r'<your/target/file_and_directories/regex/expression>')
with SevenZipFile('archive.7z', 'r') as archive:
allfiles = archive.getnames()
selective_files = [f if filter_pattern.match(f) for f in allfiles]
archive.extract(targets=selective_files)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.