【发布时间】:2020-02-06 16:39:06
【问题描述】:
我正在尝试使用 zipfile 来解压缩一系列文件。我目前的结构是这样的
ZippedFile1 Contents:
ZFC1_1
ZFC1_2
ZippedFile2 Contents:
ZippedFile (Not zipped folder)
ZFC2_2
ZFC2_2
我想要达到的结果
结果文件夹内容:
ZFC1_1
ZFC1_2
ZFC2_1
ZFC2_2
我目前使用的代码可以成功解压缩所有内容,但将压缩文件保留在一个文件夹中。如何更改我的代码以获取子文件夹下的那些文件并将它们解压缩/移动到我的主“结果”文件夹?
import os, zipfile
dir_name = r'C:\Users\username\My_Dataset'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
#os.remove(file_name) # delete zipped file```
【问题讨论】:
-
查看这个答案:stackoverflow.com/a/47632134/42346 因此,我投票决定将其作为副本关闭。
-
谢谢,问题的描述正是我想要达到的,不知何故我错过了那个线程但是;当我尝试在该线程上使用答案时,我在 init self. fp = io.open(file, filemode) PermissionError: [Errno 13] Permission denied: 'C:\\Users\\username\\My_Dataset' 即使我能够使用最初共享的脚本来处理它们。我真的不明白为什么我没有使用该脚本的权限。提前感谢您的宝贵时间。
-
澄清一下,您尝试的是哪个答案?
-
我正在尝试前三个响应(似乎第二个答案是最佳答案)所有这些都给了我 'self.fp = io.open(file, filemode) PermissionError: [ Errno 13] 权限被拒绝:'错误。我仔细检查了我仍然可以使用我共享的初始脚本处理文件。
-
我尝试了 Gerhard Götz 的答案,但没有收到 PermissionError,所以我不确定您的情况; 尤其是如果其他脚本处理文件没有问题。
标签: python python-3.x zipfile