python 2.7批量解压zip文件到目标目录
python 2.7 mass zip file extraction to target directory
我正在尝试遍历压缩文件的文件夹并将它们解压缩到目标目录。我的代码是:
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
编辑:从移动端回来,这里有一些更简洁的代码。我注意到初始代码不会 运行 因为 'filename' 实际上是该目录的文件列表。此外,将其打开为 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 代码示例。
我正在尝试遍历压缩文件的文件夹并将它们解压缩到目标目录。我的代码是:
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
编辑:从移动端回来,这里有一些更简洁的代码。我注意到初始代码不会 运行 因为 'filename' 实际上是该目录的文件列表。此外,将其打开为 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 代码示例。