课程文本中的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()来确定文件名是否表示常规文件而不是目录。)
我有以下代码:
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'“的错误信息,我知道这是由我试图压缩压缩文件引起的……但我不确定如何纠正这一点。如何才能将文件压缩并通过测试?
谢谢
发布于 2013-03-10 05:36:54
请参阅问题中的提示(可能与家庭作业相关),并思考它与您正在查看的IOError之间的关系。
其他一些提示/技巧:
verb_noun.发布于 2013-12-01 09:13:00
按照现在的编写方式,您需要在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()https://stackoverflow.com/questions/15315389
复制相似问题