归档/Zipfile python

2024-06-01 13:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

课程文本中的zipfile示例存储保存到zipfile的文件的完整路径。但是,通常zipfiles只包含一个相对路径名(当创建zipfile之后列出这些名称时,“v:\”已被删除)。在

在这个项目中,编写一个接受目录路径并只创建目录存档的函数。例如,如果使用与示例中相同的路径(“v:\workspace\Archives\src\archive_me”),则zipfile将包含“archive_me\groucho”“archive_me\harpo”和“archive_me\chico” 请注意zipfile.name列表()在返回的内容中始终使用正斜杠,在比较观察到的和预期的值时,您需要考虑到这一点。在

基本目录(上例中的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]是一个目录:'archive\u me'”我知道这是由于我试图压缩一个存档。。。。但我不知道该怎么纠正。如何才能使文件压缩并通过测试?在

谢谢


Tags: 文件pathself路径目录osdefunittest
2条回答

现在的编写方式是在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()

看到你问题中的提示(可能是与家庭作业相关的),并思考它与你看到的IOError有什么关系。在

其他一些提示/提示:

  1. 尝试在处理过程中打印信息,而不是一次打印所有内容这将有助于跟踪错误并向用户提供进度指示;

  2. 看看你是否能找到错误产生的地方,并给用户更好的反馈;

  3. 将每个功能都看作是一个工作,并查看它与my_archive所做的工作之间的关系(包括在测试中如何使用它以及在实际使用中);

  4. 函数的名称应该描述它们所做的事情通常的模式是verb_noun

相关问题 更多 >