简体   繁体   English

Python解压并将“_”添加到新提取的文件中

[英]Python unzipping and adding “_” to newly extracted file

With this code, I extract the files from the zip file, but if there is a file with the same name as the files I extracted in a different zip file, it overwrites this file.使用此代码,我从 zip 文件中提取文件,但如果存在与我在不同 zip 文件中提取的文件同名的文件,它会覆盖此文件。 I want this file to be extracted by adding the "_1" to the end.我希望通过在末尾添加“_1”来提取此文件。 Can you help me with this?你能帮我解决这个问题吗?

import zipfile, os, shutil
myZip = zipfile.ZipFile('abc.zip')    

directory_to_extract_to = "place of extraction path"

for file in myZip.filelist:
    if file.filename.endswith('.txt'):
        source = myZip.open(file)
        target = open(os.path.join(directory_to_extract_to, os.path.basename(file.filename)), "wb")

        with source, target:
            shutil.copyfileobj(source, target)

eg;例如; okay.txt >>> extract new file with the same name >>> okay_1.txt >>> okay_2.txt OK.txt >>> 提取同名的新文件 >>> OK_1.txt >>> OK_2.txt

I believe this will answer your question:我相信这会回答你的问题:

import zipfile, os, shutil

myZip = zipfile.ZipFile('abc.zip') 

directory_to_extract_to = "place of extraction path"

for i,file in enumerate(myZip.filelist):
    if file.filename.endswith('.txt'):
        if file.filename not in os.listdir(directory_to_extract_to):
            path=os.path.join(directory_to_extract_to, os.path.basename(file.filename))
        else:
            path=os.path.join(directory_to_extract_to, os.path.basename(file.filename.replace(".txt",str(i)+".txt")))
        source = myZip.open(file)
        target = open(path, "wb")

        with source, target:
            shutil.copyfileobj(source, target)

What we are doing here is, searching file name in that extracting directory if found then add iteration number in file name otherwise same as what you are doing.我们在这里所做的是,如果找到,则在该提取目录中搜索文件名,然后在文件名中添加迭代编号,否则与您正在执行的操作相同。 We are using iteration number so, you may not get the continuous number in file name but I believe, it solves your issue.我们正在使用迭代编号,因此您可能不会在文件名中获得连续编号,但我相信,它可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM