简体   繁体   English

当文件系统中不存在该文件夹时,如何在zip中添加文件夹?

[英]How to add folder in zip, when this folder does not exist in file system?

The task is to create zip archives containing a tree of folders with files. 任务是创建zip归档文件,其中包含带有文件的文件夹树。 But one nuance, these folders are not on the disk, there are only files with other names, and the tree is contained in the database. 但是,一个细微差别是,这些文件夹不在磁盘上,只有其他名称的文件,并且树包含在数据库中。

I tried to use the standard zipfile, but when I tried to call the write method I got an error that there is no such folder on the disk. 我尝试使用标准的zipfile,但是当我尝试调用write方法时,出现错误,表明磁盘上没有此类文件夹。 How can I solve this task? 我该如何解决这个任务?

To create a folder in the archive that is not on the disk, one must use the writestr() method. 要在归档文件中创建不在磁盘上的文件夹,必须使用writestr()方法。 For example: 例如:

zf.writestr('folder1/', '')

In order to write a file to the archive, while creating a number of folders that are not on the disk, one must use the write() method, where as the file name specify its name on the disk, and as an argument arcname specify the path to it in the archive. 为了将文件写入存档,在创建许多不在磁盘上的文件夹时,必须使用write()方法,其中,文件名在磁盘上指定其名称,而参数arcname指定存档中的路径。 This will create all the previous folders specified in arcname. 这将创建在arcname中指定的所有以前的文件夹。 For example: 例如:

zf.write('test.txt', arcname='folder2/test1.txt')

After these two lines in the archive will be folder 'folder1' and 'folder2' and in folder 'folder2' will be file called 'test1.txt' contains the content of file 'test.txt' from file system. 在存档的这两行之后,将是文件夹“ folder1”和“ folder2”,在文件夹“ folder2”中将是名为“ test1.txt”的文件,其中包含文件系统中文件“ test.txt”的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM