简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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