首页 > 解决方案 > 遍历目录以查找特定文件和文件夹集的脚本

问题描述

我正在尝试创建一个脚本,它将遍历所有文件夹和子文件夹以rootDir查找特定的文件夹和文件集。如果脚本将找到包含以下内容的文件夹(例如testfolder1):

它将创建包含textfile.txt, image.jpg, subtitles.dxfp(如果找到)video.mp4video_trailer.mp4(如果找到)的存档并将其保存在 rootDir 中。

目前我有递归遍历所有这些文件的片段,但它不包括那些video.mp4并且video_trailer.mp4在文件夹中。我应该如何修改我的代码以达到想要的效果?我猜它应该看开头 iftextfile.txt和被找到,如果是这样image.jpgsubtitles.dxfp它会查看是否存在包含video.mp4文件的文件夹,但不是递归的,最后它会搜索另一个包含video_trailer.mp4文件的文件夹。我对吗?我不知道我应该如何正确地用代码编写它。提前感谢您提供的任何提示,使我更接近解决方案。

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

标签: pythonoperating-systemtararchivedirectory-traversal

解决方案


使用 find 怎么样?

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

使用 -u 您可以更新现有档案。

问候,狐狸


推荐阅读