开发者

Issue in creating Zip file using glob.glob

开发者 https://www.devze.com 2022-12-31 15:55 出处:网络
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

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


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.

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()

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号