使用 glob.glob 创建 Zip 文件时出现问题
我正在从文件夹(和子文件夹)创建 Zip 文件。它工作正常并创建一个新的 .zip 文件,但我在使用 glob.glob 时遇到问题。它正在读取所需文件夹(源文件夹)中的所有文件并写入新的 zip 文件,但问题是它添加了子目录,但没有从子目录中添加文件。
我为用户提供了选择文件名和路径以及文件类型(Zip 或 Tar)的选项。我在创建 .tar.gz 文件时没有遇到任何问题,但当使用创建 .zip 文件时,会遇到此问题。
这是我的代码:
for name in (Source_Dir):
for name in glob.glob("/path/to/source/dir/*" ):
myZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
myZip.close()
另外,如果我使用下面的代码:
for dirpath, dirnames, filenames in os.walk(Source_Dir):
myZip.write(os.path.join(dirpath, filename) os.path.basename(filename))
myZip.close()
现在,第二个代码将获取所有文件,即使它位于文件夹/子文件夹内,也会创建一个新的 .zip 文件并在没有任何目录结构的情况下写入它。它甚至不采用主文件夹的目录结构,而是简单地将主目录或子目录中的所有文件写入该 .zip 文件。
任何人都可以帮助我或建议我。我更喜欢 glob.glob 而不是使用第二个选项。
提前致谢。
问候, 阿卡什
I am creating a Zip file from a folder (and subfolders). it works fine and creates a new .zip file also but I am having an issue while using glob.glob. It is reading all files from the desired folder (source folder) and writing to the new zip file but the problem is that it is, however, adding subdirectories, but not adding files form the subdirectories.
I am giving user an option to select the filename and path as well as filetype also (Zip or Tar). I don;t get any problem while creating .tar.gz file, but when use creates .zip file, this problem comes across.
Here is my code:
for name in (Source_Dir):
for name in glob.glob("/path/to/source/dir/*" ):
myZip.write(name, os.path.basename(name), zipfile.ZIP_DEFLATED)
myZip.close()
Also, if I use code below:
for dirpath, dirnames, filenames in os.walk(Source_Dir):
myZip.write(os.path.join(dirpath, filename) os.path.basename(filename))
myZip.close()
Now the 2nd code taks all files even if it inside the folder/ subfolders, creates a new .zip file and write to it without any directory strucure. It even does not take dir structure for main folder and simply write all files from main dir or subdir to that .zip file.
Can anyone please help me or suggest me. I would prefer glob.glob rather than the 2nd option to use.
Thanks in advance.
Regards,
Akash
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Glob 的设计不会扩展到子目录。它遵循 UNIX 样式路径规则和扩展,请参阅 fnmatch 的文档以获取更多信息。如果您想访问子目录,则需要将其添加到路径中。这个例子将把一切都降低一级。
Doug Hellman 在此处进行了精彩的讨论。如果您不使用 glob 的模式功能(例如对所有文本文件使用 *.txt 或对扩展名前有数字的所有文本文件使用 *[0-9].txt),那么我认为您的 os.walk 解决方案更好
Glob by design does not expand into subdirectories. It follows UNIX style path rules and expansions see the documentation for fnmatch for more information. If you want to get at the subdirectories you need to add it to the path. This example will get everything at one level down.
Doug Hellman has an excellent discussion here. If you are not using the pattern features of glob (like *.txt for all text files or *[0-9].txt for all text files that have a number before the extension) then I think your os.walk solution is better