问题
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.txtimage.jpg- (optionally)
subtitles.dxfp - another folder (ex.
testsubfolder1) containingvideo.mp4file - (optionally) another folder (ex.
testsubfolder2) containingvideo_trailer.mp4file
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