当我尝试使用以下代码压缩目录时,我的目录已压缩,并且包含我要压缩的所有文件,但是它也正在压缩我要压缩的目录的根目录。
(测试是要压缩的目标目录-它包含其他目录和文件)解压缩my_python_files.zip时,它将使用绝对路径解压缩:
解压缩my_python_files.zip:
\ Users \ hhafez \ Desktop \ Test
我想拥有的时间:
\ Test
我在设法避免这种情况时遇到了麻烦,任何提示将不胜感激。
def get_all_file_paths(directory):
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
def zipfiles():
file_paths = get_all_file_paths(r"C:\Users\hhafez\Desktop\Test")
with ZipFile('my_python_files.zip','w') as myzip:
for file in file_paths:
print(file)
myzip.write(file)
print('All files zipped successfully!')
zipfiles()
答案 0 :(得分:0)
如果要压缩文件列表,而不希望zip归档文件包含每个文件的绝对路径...
def zipFiles(directory):
parentDir = "C:\Users\hhafez\Desktop" #hardcoding parent path to strip
with ZipFile('my_python_files.zip','w') as myzip:
for root, directories, files in os.walk(directory):
zipFileName = root[len(parentDir):] #always take whats after the parentDir for the filename going in the zip
for file in files:
myzip.write(os.path.join(root,file), os.path.join(zipFileName,file), compress_type=zipfile.ZIP_DEFLATED)
zipfiles(r"C:\Users\hhafez\Desktop\Test")
这应该可以满足您的需求。这里的主要区别是zipFileName变量。
zipFileName = root[len(parentDir):]
此行从要爬网的目录中删除parentDir。 zipFileName和文件名将是传递给myzip.write的档案名称,这说明了这一点:
myzip.write(os.path.join(root,file), os.path.join(zipFileName,file), compress_type=zipfile.ZIP_DEFLATED)