python - 重命名从 zipfile 中提取的文件

标签 python zip python-zipfile

我在 Linux 服务器上有很多压缩文件,每个文件都包含多个文本文件。

我想要的是提取其中一些文本文件,这些文件在压缩文件中具有相同的名称并将其保存在一个文件夹中;我正在为每个压缩文件创建一个文件夹并将文本文件提取到其中。我需要将父压缩文件夹名称添加到文件名的末尾,并将所有文本文件保存在一个目录中。例如,如果压缩文件夹是 March132017.zip 并且我提取了 holding.txt,我的文件名将是 holding_march13207.txt。

我的问题是我无法更改提取文件的名称。 如果您能提供建议,我将不胜感激。

import os 
import sys 
import zipfile
os.chdir("/feeds/lipper/emaxx") 

pwkwd = "/feeds/lipper/emaxx" 

for item in os.listdir(pwkwd): # loop through items in dir
    if item.endswith(".zip"): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        fh = open(file_name, "rb")
        zip_ref = zipfile.ZipFile(fh)

        filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT'
        for name in filelist :
            try:
                outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0]
                zip_ref.extract(name, outpath)

            except KeyError:
                {}

        fh.close()

最佳答案

import zipfile

zipdata = zipfile.ZipFile('somefile.zip')
zipinfos = zipdata.infolist()

# iterate through each file
for zipinfo in zipinfos:
    # This will do the renaming
    zipinfo.filename = do_something_to(zipinfo.filename)
    zipdata.extract(zipinfo)

引用: https://bitdrop.st0w.com/2010/07/23/python-extracting-a-file-from-a-zip-file-with-a-different-name/

关于python - 重命名从 zipfile 中提取的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44079913/

相关文章:

python - 如何在 wsgi 应用程序中使用 gzip 编码?

python - "No such file: ' requirements.txt ' error"while installing Quartz module

haskell - 如何使用 zip 和列表理解来定义 zipWith

python - 压缩文件 : how to set a password for a Zipfile?

python - 压缩文件 : Check for correct Password

python - Octave isnan : not defined error using oct2py

python - PySide (Qt) 信号未到达我的插槽

Python - 识别压缩文件类型和解压缩的机制

python - zip、排序和 Pandas

python - 使用 zipfile 提取大文件