Python 解压缩文件并连接结果

标签 python linux python-2.7

<分区>

我的系统上有一个包含十个 zip 文件的目录。每个 zip 文件包含 1 个文本文件。我想编写一个 Python 脚本来解压缩目录中的所有文件,然后将所有生成的(解压缩的)文件连接到一个文件中。我怎样才能做到这一点?到目前为止,我有一个解压缩所有文件的脚本,但我不确定如何添加连接。以下是我所拥有的。

import os, zipfile

dir_name = '/path/to/dir'
pattern = "my-pattern*.gz"

os.chdir(dir_name)  # change directory from working dir to dir with files

for item in os.listdir(dir_name):  # loop through items in dir
    if item == pattern:  # check for my pattern extension
        file_name = os.path.abspath(item)  # get full path of files
        zip_ref = zipfile.ZipFile(file_name)  # create zipfile object
        zip_ref.extractall(dir_name)  # extract file to dir
        zip_ref.close()  # close file

最佳答案

解压缩文件时不必将文件写入磁盘,Python 可以直接从 zip 中读取文件。因此,假设除了连接结果之外您不需要任何东西,请将最后两行替换为:

for zipfile in zip_ref.namelist():
    with open('targetfile', 'a') as target:
        target.write(zip_ref.read(zipfile))

关于Python 解压缩文件并连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39431073/

相关文章:

python - Renpy 和请求

python - PyQt 5 : How to maintain relative widget size when expanding a window

java - 使用 Linux 服务器的凭据连接到 AD

python - 为什么 networkx.draw() 什么都不产生?

python - cv2.contourArea 无法正常工作

c - 在 C 中创建目录,linux 不创建子目录(目录树)——为什么?

linux - Docker 端口映射是主机到容器还是容器到主机?

python - 对于 argparse,子解析器本质上是相互排斥的吗?

python - 将字典的字典转换为列表的字典

python - 每次我访问服务器时,Django 应用程序都会显示相同的实例