重命名从 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()

原文由 Roo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 930
2 个回答

为什么不只读取有问题的文件并自己保存而不是提取?就像是:

 import os
import zipfile

source_dir = "/feeds/lipper/emaxx"  # folder with zip files
target_dir = "/SCRATCH/emaxx"  # folder to save the extracted files

# Are you sure your files names are capitalized in your zip files?
filelist = ['ISSUERS.TXT', 'SECMAST.TXT', 'FUND.TXT', 'HOLDING.TXT']

for item in os.listdir(source_dir):  # loop through items in dir
    if item.endswith(".zip"):  # check for ".zip" extension
        file_path = os.path.join(source_dir, item)  # get zip file path
        with zipfile.ZipFile(file_path) as zf:  # open the zip file
            for target_file in filelist:  # loop through the list of files to extract
                if target_file in zf.namelist():  # check if the file exists in the archive
                    # generate the desired output name:
                    target_name = os.path.splitext(target_file)[0] + "_" + os.path.splitext(file_path)[0] + ".txt"
                    target_path = os.path.join(target_dir, target_name)  # output path
                    with open(target_path, "w") as f:  # open the output path for writing
                        f.write(zf.read(target_file))  # save the contents of the file in it
                # next file from the list...
    # next zip file...

原文由 zwer 发布,翻译遵循 CC BY-SA 3.0 许可协议

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/

原文由 Saikiran Gosikonda 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题