我可以压缩文件夹,但在提取文件夹时,它还包含主目录文件夹,但我只需要它的子文件夹
ex:我选择压缩的文件夹下面
" / home / sr1 / Documents / MyFolder"
MyFolder还包含子文件夹和子文件夹编组文件
我可以压缩MyFolder但是在提取文件夹结构时
" /home/sr1/Documents/MyFolder/newDoc/file1.txt"
但它应该像
" MyFolder文件/ newDoc / FILE1.TXT"
这是我的代码
def zip_folder(folder_path, output_path):
"""Zip the contents of an entire folder (with that folder included
in the archive). Empty subfolders will be included in the archive
as well.
"""
parent_folder = os.path.dirname(folder_path)
# Retrieve the paths of the folder contents.
contents = os.walk(folder_path)
zip_file = None
try:
zip_file = zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED)
rootlen = len(folder_path) + 1
for root, folders, files in contents:
# Include all subfolders, including empty ones.
for folder_name in folders:
print " root ", root
print " relative_path " ,folder_name
absolute_path = os.path.join(root, folder_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path, relative_path)
for file_name in files:
absolute_path = os.path.join(root, file_name)
relative_path = absolute_path.replace(parent_folder + '\\',
'')
print "Adding '%s' to archive." % absolute_path
zip_file.write(absolute_path,absolute_path[rootlen:])
print "'%s' created successfully." % output_path
except IOError, message:
print message
sys.exit(1)
except OSError, message:
print message
sys.exit(1)
except zipfile.BadZipfile, message:
print message
sys.exit(1)
finally:
if zip_file :
zip_file.close()
zip_folder('/home/sr1/Documents/MyFolder','MyFolder.zip')
请帮我解决这个问题
提前致谢..