首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Archive / Zipfile python

Archive / Zipfile python
EN

Stack Overflow用户
提问于 2013-03-10 04:12:30
回答 2查看 644关注 0票数 0

课程文本中的zipfile示例存储它保存到zipfile的文件的完整路径。但是,通常情况下,zipfile只包含相对路径名(您将看到,在创建zipfile之后列出这些名称时,"v:\“已被删除)。

在这个项目中,编写一个以目录路径为参数的函数,并只创建该目录的存档。例如,如果使用与示例中相同的路径("v:\workspace\Archives\src\archive_me"),则压缩文件将包含"archive_me\groucho“、"archive_me\harpo”和“archive_me\chico”。请注意,zipfile.namelist()总是在返回的内容中使用正斜杠,在比较观察值和期望值时,需要考虑到这一点。

基本目录(上面示例中的“archive_me”)是输入的最后一个元素,zipfile中记录的所有路径都应该从基本目录开始。

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

我有以下代码:

代码语言:javascript
复制
 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'“的错误信息,我知道这是由我试图压缩压缩文件引起的……但我不确定如何纠正这一点。如何才能将文件压缩并通过测试?

谢谢

EN

回答 2

Stack Overflow用户

发布于 2013-03-10 05:36:54

请参阅问题中的提示(可能与家庭作业相关),并思考它与您正在查看的IOError之间的关系。

其他一些提示/技巧:

  1. 尝试在处理过程中打印信息,而不是一次打印所有内容--这将有助于跟踪错误,并为用户提供进度指示;
  2. 查看您是否可以找到错误产生的位置,并向用户提供更好的反馈;
  3. 将每个函数视为正在执行一项工作,并查看这与my_archive所做的工作有何关系(无论是在测试中还是在实际使用中);
  4. 函数的名称应该描述它们所做的事情--通常的模式是verb_noun.
票数 0
EN

Stack Overflow用户

发布于 2013-12-01 09:13:00

按照现在的编写方式,您需要在for循环的每次迭代之后关闭zipfile。另外,您的zipfile的名称与您的目标目录相同,请尝试以下命令:

代码语言:javascript
复制
#!/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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15315389

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档