-->

如何读取的7z文件使用Python的内容如何读取的7z文件使用Python的内容(How to re

2019-05-12 05:37发布

我怎样才能读取和保存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)

Answer 1:

您可以使用libarchive或pylzma 。 如果你可以升级到python3.3 +你可以使用LZMA ,这是在标准库。



Answer 2:

脱壳而出,并呼吁7Z将提取的文件,然后你可以访问使用标准的文件访问调用这些文件(我不知道Python的 - 但它必须能够访问文件)。

如果你想看看Python的范围内直接向7z压缩归档中,那么你就需要使用图书馆。 这里有一个: https://pypi.python.org/pypi/libarchive -正如我说我不能保证它-我不是一个Python用户-但使用第三方库通常是在所有的语言很容易。

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

希望帮助。



Answer 3:

我结束了在这种情况下,我被迫使用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

以及如何解析与蟒蛇是输出:

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 colts.zip', shell=True)
str_result = byte_result.decode('utf-8')
line_result = str_result.splitlines()
files = parse_lines(line_result)


文章来源: How to read contents of 7z file using python