0

课程文本中的 zipfile 示例存储了它保存到 zipfile 的文件的完整路径。然而,通常情况下,zip 文件只包含一个相对路径名(您会看到,在创建 zip 文件后列出名称时,“v:\”已被删除)。

在这个项目中,编写一个函数,该函数采用目录路径并仅创建目录的存档。例如,如果使用与示例中相同的路径(“v:\workspace\Archives\src\archive_me”),则 zip 文件将包含“archive_me\groucho”、“archive_me\harpo”和“archive_me\chico”。请注意, zipfile.namelist() 在其返回的内容中始终使用正斜杠,在比较观察到的和预期的内容时需要适应这一事实。

基本目录(上例中的“archive_me”)是输入的最后一个元素,并且 zipfile 中记录的所有路径都应以基本目录开头。

如果目录包含子目录,则不应包含子目录名称和子目录中的任何文件。(提示:您可以使用 isfile() 来确定文件名是否代表常规文件而不是目录。)

我有以下代码:

 import os, shutil, zipfile, unittest

 def my_archive(path):
     x = os.path.basename(path)
     zf = zipfile.ZipFile(x, "w")
     filenames = glob.glob(os.path.join(x, "*"))
     print(filenames)
     for fn in filenames:
          zf.write(fn)
          zf.close
     zf = zipfile.ZipFile(path)
     lst =  zf.namelist()
     return(lst)
     zf.close()


 import os, shutil, zipfile, unittest
 import archive_dir

 class TestArchiveDir(unittest.TestCase):

     def setUp(self):
         self.parentPath = r"/Users/Temp"
         self.basedir = 'archive_me'
         self.path = os.path.join(self.parentPath,self.basedir)
         if not os.path.exists(self.path):
             os.makedirs(self.path)
         self.filenames = ["groucho", "harpo", "chico"]
         for fn in self.filenames:
             f = open(os.path.join(self.path, fn), "w")
             f.close()

     def test_archive_create(self):

         observed = archive_dir.my_archive(self.path)
         expected = ["archive_me/groucho", "archive_me/harpo", "archive_me/chico"]
         self.assertEqual(set(expected), set(observed))

     def tearDown(self):
         try:
             shutil.rmtree(self.parentPath, ignore_errors=True)
         except IOError:
             pass

 if __name__=="__main__":
     unittest.main()

我收到“IOError: [Errno 21] Is a directory: 'archive_me'”的错误我知道这是由于我试图压缩档案造成的......但我不知道如何纠正这个问题。如何让文件压缩并通过测试?

谢谢

4

2 回答 2

0

查看您问题中的提示(可能与作业相关)并考虑它与您所看到的 IOError 的关系。

其他一些提示/提示:

  1. 在处理事情时尝试打印信息,而不是一次打印所有内容——这将有助于追踪错误并为用户提供进度指示;

  2. 看看能不能定位到产生错误的地方,给用户更好的反馈;

  3. 将每个功能视为一项工作,并了解它与 my_archive 正在做什么(无论是在测试中如何使用它,还是在实际使用中);

  4. 函数的名称应该描述它们的作用——通常的模式是verb_noun.

于 2013-03-09T21:36:54.203 回答
0

现在的编写方式是在 for 循环的每次迭代后关闭 zipfile。此外,您的 zipfile 的名称与您的目标目录相同,请尝试以下操作:

#!/usr/bin/python3

import zipfile
import os
import glob

def archdir(dir):
    x = os.path.basename(dir) + ".zip"
    zf = zipfile.ZipFile(x, "w")
    filenames = glob.glob(os.path.join(os.path.basename(dir), "*"))
    print(filenames)
    for fn in filenames:
        zf.write(fn)
    zf.close()
于 2013-12-01T01:12:59.590 回答