Python 在以下文件夹/目录中查找zip文件名并将其解压缩到同一目录中的新文件夹?
我使用了Python 在以下文件夹/目录中查找zip文件名并将其解压缩到同一目录中的新文件夹?,python,python-3.x,file-format,shutil,os.walk,Python,Python 3.x,File Format,Shutil,Os.walk,我使用了os.walk()将文件列表获取到数据帧。现在我想从DataFrame中的文件列表中提取zip文件夹 DataFrame file_name base_name extension absolute_path rel_path file_1.pdf file_1 pdf C:\\temp\documents\file_1.pdf \file_1.pdf file_2.zip file_2 zip C
os.walk()
将文件列表获取到数据帧。现在我想从DataFrame中的文件列表中提取zip文件夹
DataFrame
file_name base_name extension absolute_path rel_path
file_1.pdf file_1 pdf C:\\temp\documents\file_1.pdf \file_1.pdf
file_2.zip file_2 zip C:\\temp\documents\file_2.zip \file_2.zip
file_3.7z file_3 7z C:\\temp\documents\file_3.7z \file_3.7z
file_4.tar file_4 tar C:\\temp\documents\file_4.tar \file_4.tar
注意:不能更改用于提取的包装。只有舒蒂尔包装 打开压缩文件夹的替代方法是ZIP文件。 必须使用pip安装或任何其他安装程序(例如,conda)安装库 导入列表中的代码为
import os
import fnmatch
from zipfile import ZipFile
新代码:
dirPath = 'C:\\temp' #Windows format
formats = ['*.zip','*.tar','*.7z']
for f in formats:
for file in os.listdir(dirPath):
if fnmatch.fnmatch(file,f):
os.chdir(dirPath) #change where to open zipFile
with ZipFile(file,'r') as zfiles:
flist = zfiles.namelist()
for zipped in flist:
zfiles.extract(zipped,dirPath)
如果要提取到其他目录,请更改以下行中的变量dirPath:
zfiles.extract(zipped,dirPath)
好的,我会重申我的问题。文件的位置已跟踪到数据帧。数据帧包含该特定文件的绝对路径和相对路径。现在我想执行一种递归,只将扩展名为zip的文件解压缩到同一目录下的另一个文件夹中。我更改了整个代码,以允许解压缩整个文件夹以及单个压缩文件。它不起作用。当我试图转换zip文件时,出现了一个错误“ReadError:zsnh3-15s-0003_0_bl.zip不是zip文件”。但是,当我尝试使用同一个文件直接使用shutil进行转换时,效果很好。另外,fformat中f的fformat
与格式变量#要解压缩的文件类型相同。请检查我添加的新注释。@DeepakHarish检查我为解压缩文件和文件夹而编写的新代码,如下所示well@DeepakHarish你看到新代码了吗?有帮助吗?