gpt4 book ai didi

python 2.7批量压缩文件解压到目标目录

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:16 24 4
gpt4 key购买 nike

我正在尝试遍历压缩文件的文件夹并将它们解压缩到目标目录。我的代码是:

import os
import zipfile

def mass_extract():
source_directory = raw_input("Where are the zips? ")

if not os.path.exists(source_directory):
print "Sorry, that folder doesn't seem to exist."
source_directory = raw_input("Where are the zips? ")

target_directory = raw_input("To where do you want to extract the files? ")
if not os.path.exists(target_directory):
os.mkdir(target_directory)

for path, directory, filename in os.walk(source_directory):
zip_file = zipfile.ZipFile(filename, 'w')
zipfile.extract(zip_file, target_directory)
zip_file.close()

print "Done."

这里有两个错误:

AttributeError: 'module' object has no attribute 'extract'
Exception AttributeError:"'list' object has no attribute 'tell'" in <bound method ZipFile.__del__ of <zipfile.ZipFile object at 0xb701d52c>> ignored

有什么问题吗?

最佳答案

尝试将 zipfile.extract 更改为 zip_file.extractall

编辑:从移动端回来,这里有一些更简洁的代码。我注意到初始代码不会按原样运行,因为“文件名”实际上是该目录的文件列表。此外,以 write 又名 w 打开它只会覆盖您现有的 zip 文件,您不希望这样。

for path, directory, filenames in os.walk(source_directory):
for each_file in filenames:
file_path = os.path.join(path, each_file)
if os.path.splitext(file_path)[1] == ".zip": # Make sure it's a zip file
with zipfile.ZipFile(file_path) as zip_file:
zip_file.extractall(path=target_directory)

Here是我刚才使用的 zipfile 代码示例。

关于python 2.7批量压缩文件解压到目标目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35439255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com