如何使用Python压缩目录(使用zipfile)

我相对较新的python,我试图压缩目录包含几个级别的文件和文件夹。我可以使用函数每个文件的名字在我的目录,我可以使用zipfile zip平坦的文件在一个文件夹,但是我的时间努力压缩整个目录。我想zip文件称为"帮助。邮政",我想让它保留原始文件结构。我的一些尝试,这里是最新的:

选择 | 换行 | 行号
  1. import zipfile, os
  2.  
  3. def main():
  4.     zip = "help3.zip"
  5.     directory = "//groupstore/workgroups/documentation/test"
  6.     toZip(directory)
  7.  
  8.  
  9. def toZip(directory):
  10.     zippedHelp = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
  11.  
  12.     list = os.listdir(directory)
  13.  
  14.     for entity in list:
  15.         each = os.path.join(directory,entity)
  16.  
  17.         if os.path.isfile(each):
  18.             print each
  19.             zippedHelp.write(each,zipfile.ZIP_DEFLATED)
  20.         else:
  21.             addFolderToZip(zippedHelp,entity)
  22.  
  23.     zippedHelp.close()
  24.  
  25. #def addFolderToZip(zippedHelp,folder):
  26.  
  27.     for file in folder:
  28.             if os.path.isfile(file):
  29.                 zippedHelp.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
  30.             elif os.path.isdir(file):
  31.                 addFolderToZip(zippedHelp,file)
  32. main()
  33.  
# 回答1

这是另一个线程可能有关:http://bytes.com/forum/thread845051.html
# 回答2

我这里有一个脚本,该脚本使用备份的内容目录和子目录。它可以很容易地调整只备份的目录或文件内容与特定的扩展。保存在档案文件路径。

选择 | 换行 | 行号
  1. import zipfile, os
  2.  
  3. def makeArchive(fileList, archive):
  4.     """
  5.     'fileList' is a list of file names - full path each name
  6.     'archive' is the file name for the archive with a full path
  7.     """
  8.     try:
  9.         a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
  10.         for f in fileList:
  11.             print "archiving file %s" % (f)
  12.             a.write(f)
  13.         a.close()
  14.         return True
  15.     except: return False
  16.  
  17. def dirEntries(dir_name, subdir, *args):
  18.     '''Return a list of file names found in directory 'dir_name'
  19.     If 'subdir' is True, recursively access subdirectories under 'dir_name'.
  20.     Additional arguments, if any, are file extensions to match filenames. Matched
  21.         file names are added to the list.
  22.     If there are no additional arguments, all files found in the directory are
  23.         added to the list.
  24.     Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py')
  25.         Only files with 'txt' and 'py' extensions will be added to the list.
  26.     Example usage: fileList = dirEntries(r'H:\TEMP', True)
  27.         All files and all the files in subdirectories under H:\TEMP will be added
  28.         to the list.
  29.     '''
  30.     fileList = []
  31.     for file in os.listdir(dir_name):
  32.         dirfile = os.path.join(dir_name, file)
  33.         if os.path.isfile(dirfile):
  34.             if not args:
  35.                 fileList.append(dirfile)
  36.             else:
  37.                 if os.path.splitext(dirfile)[1][1:] in args:
  38.                     fileList.append(dirfile)
  39.         # recursively access file names in subdirectories
  40.         elif os.path.isdir(dirfile) and subdir:
  41.             print "Accessing directory:", dirfile
  42.             fileList.extend(dirEntries(dirfile, subdir, *args))
  43.     return fileList
  44.  
  45. if __name__ == '__main__':
  46.     folder = r'D:\Zip_Files\611 Lenox'
  47.     zipname = r'D:\Zip_Files\611 Lenox\test.zip'
  48.     makeArchive(dirEntries(folder, True), zipname)
  49.  

HTH

# 回答3

谢谢!我很感谢帮助!
# 回答4

谢谢你! !耶。我用你的脚本使我的工作和我得到更好的理解递归函数。这绝对是我的难题。再次感谢! !
# 回答5

@bvdet谢谢,这正是我一直在寻找在我pys60应用:D。再次感谢你的帮助:)
# 回答6

你也可以做到这一点,更简洁:

选择 | 换行 | 行号
  1. def recursive_zip(zipf, directory, folder=None):
  2.     list = os.listdir(directory)
  3.  
  4.     for file in list:
  5.         if os.path.isfile(file):
  6.             zipf.write(file, folder, zipfile.ZIP_DEFLATED)
  7.         elif os.path.isdir(file):
  8.             recursive_zip(zipf, os.path.join(directory, file), file)
# 回答7

Nakubu,谢谢你的贡献。发帖时请使用代码标记代码。这不是一个好主意列表和文件变量的名字。内置的功能列表()和文件()将蒙面,直到被删除的对象。我有一个问题。是zipf一个打开的文件对象?是很有帮助的其他阅读这个线程如果你想发布示例代码创建file对象,调用recursive_zip (),然后关闭文件对象。BV——主持人
# 回答8

这里有一个修订版本:

选择 | 换行 | 行号
  1. def recursive_zip(zipf, directory, folder=None):
  2.     nodes = os.listdir(directory)
  3.  
  4.     for item in nodes:
  5.         if os.path.isfile(item):
  6.             zipf.write(item, folder, zipfile.ZIP_DEFLATED)
  7.         elif os.path.isdir(item):
  8.             recursive_zip(zipf, os.path.join(directory, item), item)
  9.  
  10.  

zipf zipfile打开。ZipFile实例。例如:

选择 | 换行 | 行号
  1. zipf = zipfile.ZipFile(zip, "w", compression=zipfile.ZIP_DEFLATED )
  2. path = '/Users/nakubu/some_folder'
  3. recursive_zip(zipf, path) //leave the first folder as None, as path is root.
  4. zipf.close()
  5.  
# 回答9

我发现Nakubu的功能有帮助,但在很多方面需要修改它。希望这可以帮助别人:

选择 | 换行 | 行号
  1. def recursive_zip(zipf, directory, folder = ""):
  2.    for item in os.listdir(directory):
  3.       if os.path.isfile(os.path.join(directory, item)):
  4.          zipf.write(os.path.join(directory, item), folder + os.sep + item)
  5.       elif os.path.isdir(os.path.join(directory, item)):
  6.          recursive_zip(zipf, os.path.join(directory, item), folder + os.sep + item)
  7.  
# 回答10

这些都是很好的,但恕我直言,操作系统。岩石和为你做困难的东西走。

标签: python

添加新评论