简体   繁体   English

使用Python将文件解压缩到一个文件夹

[英]Unzip files using Python to one folder

I want to unzip files with python 2.7.8 .When i try to extract zip files that contain files with same names in it to one folder, some files got lost because duplication names. 我想用python 2.7.8解压缩文件。当我尝试将包含相同名称的文件的zip文件提取到一个文件夹中时,由于重复的名称,一些文件丢失了。 I try that: 我尝试:

import zipfile,fnmatch,os

rootPath = r"C:\zip"
pattern = '*.zip'
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print(os.path.join(root, filename))
        outpath = r"C:\Project\new"  
        zipfile.ZipFile(os.path.join(root, filename)).extractall(r"C:\Project\new")

UPDATE: 更新:

I try to extract all the files located inside the zip files into one folder only without a new subfolders created. 我尝试仅将zip文件中的所有文件都提取到一个文件夹中,而不创建新的子文件夹。 If there are files with the same name i need all the files 如果有同名的文件,我需要所有文件

The ZipFile.extractall() method simply extracts the files and stores them one by one in the target path. ZipFile.extractall()方法仅提取文件并将它们一一存储在目标路径中。 If you want to preserve files with duplicated names you will have to iterate over the members using ZipeFile.namelist() and take appropriate action when you detect duplicates. 如果要保留名称重复的文件,则必须使用ZipeFile.namelist()遍历成员,并在检测到重复项时采取适当的措施。 The ZipFile.read() allows you to read the file contents, then you can write them wherever (and with whatever name) you want. ZipFile.read()允许您读取文件内容,然后可以将其写入所需的任何位置(并使用任何名称)。

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

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