如何使用python读取7z文件的内容

Ken*_*Kem 16 7zip python-2.7

如何阅读和保存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)
Run Code Online (Sandbox Code Playgroud)

Zho*_*gbo 12

如果你可以使用python 3,有一个有用的库py7zr,它支持7zip存档压缩、解压、加密和解密。

import py7zr
with py7zr.SevenZipFile('sample.7z', mode='r') as z:
    z.extractall()
Run Code Online (Sandbox Code Playgroud)


小智 10

您可以使用libarchivepylzma.如果你可以升级到python3.3 +,你可以使用标准库中的lzma.

  • 请注意,lzma不适用于7z*archives*,仅适用于单个文件. (45认同)
  • 所以lzma不是正确的库,我只是浪费时间让它工作.Downvote. (8认同)
  • 默认情况下,“libarchive”在 **Windows** 上不起作用。安装将失败,并出现以下错误:“无法加载库:找不到模块“libarchive.so”。”...您必须自己编译 libarchive.dll 并添加它 - 以及它所依赖的其他几个 .dll on - 到您的系统路径识别的某个文件夹。 (3认同)
  • 我总是使用python 2.7.9,我不知道3.3+有7z的标准库,所以非常感谢你 (2认同)

Kyl*_*ton 7

我最终遇到了被迫使用 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
Run Code Online (Sandbox Code Playgroud)

以及如何使用 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)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,整个代码可以简化为 `[l.split()[-1] for l in str_result.rsplit("\n\n",1)[-1].splitlines()[2:-2]] `。 (2认同)

小智 1

删除并调用 7z 将提取文件,然后您就可以使用open()这些文件。

如果您想直接在 Python 中查看 7z 存档,那么您需要使用一个库。这是一个: https: //pypi.python.org/pypi/libarchive - 正如我所说,我不能保证这一点 - 我不是 Python 用户 - 但在所有语言中使用第三方库通常都很容易。

一般来说,7z 支持似乎有限。如果您可以使用替代格式(zip/gzip),那么我想您会发现 Python 库(和示例代码)的范围更加全面。

希望有帮助。