将python 2.7 mass zip文件提取到目标目录
我试图遍历压缩文件的文件夹,并将它们解压缩到目标目录。我的代码是:将python 2.7 mass zip文件提取到目标目录,python,zipfile,os.walk,Python,Zipfile,Os.walk,我试图遍历压缩文件的文件夹,并将它们解压缩到目标目录。我的代码是: 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." s
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
AttributeError:'module'对象没有属性'extract'
异常AttributeError:“list”对象在忽略中没有属性“tell”
有什么问题吗?尝试将
zipfile.extract
更改为zip\u文件。extractall
编辑:从手机回来,这里有一些更干净的代码。我注意到初始代码不会按原样运行,因为“filename”实际上是该目录的文件列表。另外,以write
akaw
打开它只会覆盖现有的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)
是我刚才使用的zipfile代码的一个示例 这两个错误都可能是因为它是
zip\u文件
对象的成员,而不是zipfile
模块。使用上下文管理器:和zipfile.zipfile(文件名,'w')作为zip\u文件是很好的形式: