如何读取并保存7z的内容。我使用Python 2.7.9,我可以像这样提取或存档,但我无法读取Python中的内容,我只在CMD中列出文件的内容
import subprocess
import os
source = 'filename.7z'
directory = 'C:\Directory'
pw = '123456'
subprocess.call(r'"C:\Program Files (x86)\7-Zip\7z.exe" x '+source +' -o'+directory+' -p'+pw)
如果你会使用python 3,有一个有用的库py7zr,它支持7zip存档压缩、解压、加密和解密。
import py7zr
with py7zr.SevenZipFile('sample.7z', mode='r') as z:
z.extractall()
我最终陷入了被迫使用 7z 的境地,并且还需要确切地知道从每个 zip 存档中提取了哪些文件。为了解决这个问题,您可以检查 7z 调用的输出并查找文件名。 7z 的输出如下所示:
$ 7z l sample.zip
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21
p7zip Version 16.02 (locale=utf8,Utf16=on,HugeFiles=on,64 bits,8 CPUs x64)
Scanning the drive for archives:
1 file, 472 bytes (1 KiB)
Listing archive: sample.zip
--
Path = sample.zip
Type = zip
Physical Size = 472
Date Time Attr Size Compressed Name
------------------- ----- ------------ ------------ ------------------------
2018-12-01 17:09:59 ..... 0 0 sample1.txt
2018-12-01 17:10:01 ..... 0 0 sample2.txt
2018-12-01 17:10:03 ..... 0 0 sample3.txt
------------------- ----- ------------ ------------ ------------------------
2018-12-01 17:10:03 0 0 3 files
以及如何使用 python 解析该输出:
import subprocess
def find_header(split_line):
return 'Name' in split_line and 'Date' in split_line
def all_hyphens(line):
return set(line) == set('-')
def parse_lines(lines):
found_header = False
found_first_hyphens = False
files = []
for line in lines:
# After the header is a row of hyphens
# and the data ends with a row of hyphens
if found_header:
is_hyphen = all_hyphens(''.join(line.split()))
if not found_first_hyphens:
found_first_hyphens = True
# now the data starts
continue
# Finding a second row of hyphens means we're done
if found_first_hyphens and is_hyphen:
return files
split_line = line.split()
# Check for the column headers
if find_header(split_line):
found_header=True
continue
if found_header and found_first_hyphens:
files.append(split_line[-1])
continue
raise ValueError("We parsed this zipfile without finding a second row of hyphens")
byte_result=subprocess.check_output('7z l sample.zip', shell=True)
str_result = byte_result.decode('utf-8')
line_result = str_result.splitlines()
files = parse_lines(line_result)
您可以使用 libarchive-c 或 pylzma。如果你可以升级到python3.3+,你可以使用标准库中的lzma。
编辑 2024.01.01:将链接从
libarchive
更改为 libarchive-c
,因为前者不再处于开发阶段,而新链接即使在 Windows 上也可以轻松使用 libarchive 库。
!pip install pyunpack
!pip install patool
from pyunpack import Archive
Archive('7z file source').extractall('destination')
https://pypi.org/project/patool/
https://pypi.org/project/pyunpack/
删除并调用 7z 将提取文件,然后您可以
open()
这些文件。
如果您想直接在 Python 中查看 7z 存档,那么您需要使用一个库。这是一个:https://pypi.python.org/pypi/libarchive - 正如我所说,我不能保证这一点 - 我不是 Python 用户 - 但使用第 3 方库通常非常容易语言。
一般来说,7z 支持似乎有限。如果您可以使用替代格式(zip/gzip),那么我想您会发现 Python 库(和示例代码)的范围更加全面。
希望有帮助。
这是我如何使用 Python 获取
test.7z
中所有文件的列表:
from subprocess import Popen, PIPE
proc = Popen([r"C:\Program Files\7-Zip\7z.exe", "l", "-ba", "-slt", "test.7z"], stdout=PIPE)
files = [l.split('Path = ')[1] for l in proc.stdout.read().decode().splitlines() if l.startswith('Path = ')]
遵循使用 7zip 命令行列出 zip 文件的内容以及非详细的机器友好输出中的方法。
如果您不想安装另一个依赖包,这是一个有用的解决方案。
通过执行此操作提取目录中的所有 .7z 文件。
首先,安装
!pip install patool
!pip install pyunpack
然后
import os
from pyunpack import Archive
path = "path_to_file"
file_type = '.7z'
for filename in os.listdir(path=path):
if filename.endswith(file_type):
print(filename)
print(f"{path}/{filename}")
Archive(f"{path}/{filename}").extractall(f"{path}")```