python - 如何在多个子目录中找到具有相同扩展名的所有文件并使用 python 将它们移动到单独的文件夹中?
问题描述
我已将旧摄像机的内容复制到我的计算机上,在转移到那里的文件夹中,有 100 多个子文件夹,所有这些子文件夹都包含我想要的 6 或 7 个文件。如何能够搜索所有这些并将所有找到的文件移动到新文件夹?我对此很陌生,所以欢迎任何帮助。
解决方案
要找到所有文件,有两种方法:
- 使用 os.walker
例子:
import os
path = 'c:\\location_to_root_folder\\'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.mpg' in file:
files.append(os.path.join(r, file))
for f in files:
print(f)
- 使用 glob 示例:
import glob
path = 'c:\\location_to_root_folder\\'
files = [f for f in glob.glob(path + "**/*.mpg", recursive=True)]
for f in files:
print(f)
要移动,您可以使用以下 3 种方法中的任何一种,我个人更喜欢 shutil.move:
import os
import shutil
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
推荐阅读
- amazon-redshift - Grafana Dashboard 可以显示以前获取的数据吗?
- python - Python - 调用 exec() 的函数看不到变量
- youtube-api - Youtube 数据 API 配额何时适用?
- swift - 单击 SwiftUI 时选择 TextField 中的所有文本
- java - 创建一个 JLabels 数组 - 为什么会出现这个奇怪的错误?
- javascript - 将反应添加到一个简单的项目
- azure - AutoML“可用训练行数少于请求的 CV 拆分总数”
- amazon-web-services - 在 AWS Amplify GraphQL DynamoDB 中按另一个表的字段(也称为交叉表或嵌套过滤)过滤列表查询
- java - 我找不到 ViewPager2 的 AppCompatTextView(捕获屏幕)
- charts - 蜡烛图 - 如何计算缺失的蜡烛