Scripts traversing through directories looking for specific set of files and folders

跟風遠走 提交于 2020-03-25 17:34:45

问题


I'm trying to create a script that will traverse through all folders and subfolders of rootDir looking for specific set of folders and files. If script will find the folder (for ex. testfolder1) in which there are:

  • textfile.txt
  • image.jpg
  • (optionally) subtitles.dxfp
  • another folder (ex. testsubfolder1) containing video.mp4 file
  • (optionally) another folder (ex. testsubfolder2) containing video_trailer.mp4 file

it will create archive containing textfile.txt, image.jpg, subtitles.dxfp(if they were in found), video.mp4 and video_trailer.mp4 (if it was found) and save it in rootDir.

Currently I have snippet that traverse recursively looking for all those files, but it's not including that video.mp4 and video_trailer.mp4 are in folders. How should I modify my code in order to achieve wanted effect? I guess it should look at the beginning if textfile.txt, image.jpg and subtitles.dxfp were found, if so it looks if there exist folder containing video.mp4 file, but not recursively and at the end it searches for another folder containing video_trailer.mp4 file. Am i right? I do not know how should i properly write it in code. Thank you in advance for any tips bringing me closer to the solution.

for dirpath, dirnames, filenames in os.walk(rootDir):
    jpg = glob.glob(os.path.join(rootDir, dirpath, '*.jpg'))
    mp4 = glob.glob(os.path.join(rootDir, dirpath, '*.mp4'))
    txt = glob.glob(os.path.join(rootDir, dirpath, '*.txt'))
    xml = glob.glob(os.path.join(rootDir, dirpath, '*.xml'))
    dxfp = glob.glob(os.path.join(rootDir, dirpath, '*.dxfp'))

    if jpg and mp4 and txt:
        if xml and dxfp:
            #Archive will have the same name as image
            tarName  = [i for i in filenames if ".jpg" in i] 
            tar = tarfile.open("{0}.tar".format(tarName[0].replace(".jpg","")), "w")

            for file in [jpg, mp4, txt, xml, dxfp]:
                tar.add(file[0])
            tar.close()
        else:
            tarName  = [i for i in filenames if ".jpg" in i] 
            tar = tarfile.open("{0}.tar".format(tarName[0].replace(".jpg","")), "w")
            for file in [jpg, mp4, txt]:
                tar.add(file[0])
            tar.close()

回答1:


what about using find?

find / -type f -name "*.jpg" -exec tar -czf /tmp/jpg.tar.gz {} \;

with -u you can update existing archives.

Greetings, fuchs



来源:https://stackoverflow.com/questions/60724851/scripts-traversing-through-directories-looking-for-specific-set-of-files-and-fol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!