【发布时间】:2016-08-30 12:08:55
【问题描述】:
我的文件夹结构为:
/sample/debug/
--debug.exe
--sample.exe
--sample.pdb
--debug.pdb
--sample.dll
--debug.dll
/config
--sample.txt
--new.txt
/general
--general.txt
--code.txt
所以,我想要的只是压缩 debug 中的文件,而不是像 /config 和 /general 这样的子文件夹。我尝试如下:
import zipfile
import os
def append( dir_name ):
ret_val = []
fileList = []
for file in os.listdir(dir_name):
try:
dirfile = os.path.join(dir_name, file)
except Exception:
err = sys.exc_info()
print ("Error!", err)
fileList.append(dirfile)
ret_val = fileList
return ret_val
def zip( fileList, archive, root ):
ret_val = 0
try:
zip_folder_contents = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
except Exception:
err = sys.exc_info()
print ("Error!",err)
exit( 1 )
for filename in fileList:
zip_folder_contents.write(filename,
filename[len(root):].lstrip(os.path.sep).lstrip(os.path.altsep))
zip_folder_contents.close()
return ret_val
make(append_files_in_zipfolder("D:/sample/debug"), "debug.zip",
"D:/sample/debug")
现在当我在上面执行时,我收到错误,因为权限被拒绝“D:/sample/debug\\config”。因此,我无法删除此错误,因此我认为只包含 zip 文件夹中的文件并排除子文件夹。那么,无论如何,有没有办法做到这一点,或者我可以通过某种方式删除我得到的这个与权限相关的错误。请提出建议。
【问题讨论】:
-
什么是
make()?函数append_files_in_zipfolder()的定义在哪里? -
查看
os模块的Files and Directories部分,选择一些可以帮助您清除目录的方法,制定一些清除目录的逻辑,将它们放在一起并压缩文件.os.walk可能有点矫枉过正,但它可能会让事情变得简单。还有一些其他的可以使它变得容易/可能。