PyLZMAを使用して、アーカイブ(test.7zなど)からファイルを抽出し、同じディレクトリに抽出したいと思います。
私はPythonの初心者で、どのように始めればよいかわかりません。私はいくつかのグーグルを行い、いくつかの例とドキュメントを見つけましたが、それらがどのように機能するのか理解していません。
誰かが私がやりたいことの基本的なコードを投稿して、私が仕事を始めて理解できるようにしてくれませんか?
基本的な機能を処理する Python クラスを次に示します。私は自分の仕事にそれを使用しました:
import py7zlib
class SevenZFile(object):
@classmethod
def is_7zfile(cls, filepath):
'''
Class method: determine if file path points to a valid 7z archive.
'''
is7z = False
fp = None
try:
fp = open(filepath, 'rb')
archive = py7zlib.Archive7z(fp)
n = len(archive.getnames())
is7z = True
finally:
if fp:
fp.close()
return is7z
def __init__(self, filepath):
fp = open(filepath, 'rb')
self.archive = py7zlib.Archive7z(fp)
def extractall(self, path):
for name in self.archive.getnames():
outfilename = os.path.join(path, name)
outdir = os.path.dirname(outfilename)
if not os.path.exists(outdir):
os.makedirs(outdir)
outfile = open(outfilename, 'wb')
outfile.write(self.archive.getmember(name).read())
outfile.close()
ここに私が見つけた2つのコードスニペットがありますhttp://www.linuxplanet.org/blogs/?cat=3845
# Compress the input file (as a stream) to a file (as a stream)
i = open(source_file, 'rb')
o = open(compressed_file, 'wb')
i.seek(0)
s = pylzma.compressfile(i)
while True:
tmp = s.read(1)
if not tmp: break
o.write(tmp)
o.close()
i.close()
# Decomrpess the file (as a stream) to a file (as a stream)
i = open(compressed_file, 'rb')
o = open(decompressed_file, 'wb')
s = pylzma.decompressobj()
while True:
tmp = i.read(1)
if not tmp: break
o.write(s.decompress(tmp))
o.close()
i.close()