python - 遍历目录以查找特定文件和文件夹集的脚本
问题描述
我正在尝试创建一个脚本,它将遍历所有文件夹和子文件夹以rootDir
查找特定的文件夹和文件集。如果脚本将找到包含以下内容的文件夹(例如testfolder1
):
textfile.txt
image.jpg
- (可选)
subtitles.dxfp
- 另一个包含文件的文件夹(例如
testsubfolder1
)video.mp4
- (可选)另一个文件夹(例如
testsubfolder2
)包含video_trailer.mp4
文件
它将创建包含textfile.txt
, image.jpg
, subtitles.dxfp
(如果找到)video.mp4
和video_trailer.mp4
(如果找到)的存档并将其保存在 rootDir 中。
目前我有递归遍历所有这些文件的片段,但它不包括那些video.mp4
并且video_trailer.mp4
在文件夹中。我应该如何修改我的代码以达到想要的效果?我猜它应该看开头 iftextfile.txt
和被找到,如果是这样image.jpg
,subtitles.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()
解决方案
使用 find 怎么样?
find / -type f -name "*.jpg" -exec tar -czf /tmp/jpg.tar.gz {} \;
使用 -u 您可以更新现有档案。
问候,狐狸
推荐阅读
- c# - C++/CLI 混合托管/本机 DLL 不起作用
- javascript - JS将数组的值添加到对象
- java - 如何将 Long 列表发送到休息控制器 Spring Boot
- kubernetes - 从 Kubernetes pod/容器内部识别节点的区域
- php - 如何通过 AJAX 运行 SQL 选择查询(实时结果)
- python - Python Top 胜过
- java - 在 shell 脚本中的 oracle DB 上的 execute.sql 文件
- html - css 对包含标签的 p 标签进行分词
- php - 最小化 GitHub 上传 codeigniter 框架
- javascript - Angular 应用程序未在 Edge 中打开它重定向到在 IE 11 中自动打开