python - 如何遍历文件夹中的文件以移动具有特定扩展名的每个文件
问题描述
我复制了一个用于下载 YouTube 视频的脚本,目前正在对其进行调整。问题是,我找不到将下载的音乐移动到所需文件夹的方法。
os.chdir(r'C:\Users\vucin\Desktop\YouTube Download')
#Downloading songs
with youtube_dl.YoutubeDL(download_options) as dl:
with open('songs.txt', 'r') as f:
for song_url in f:
dl.download([song_url])
#Moving files
for file in os.walk():
if '.mp3' in file:
shutil.move('C:\\Users\\vucin\\Desktop\\YouTube Download\\file',
r'C:\Users\vucin\Desktop\Muzika')
input()
解决方案
从 Python 3.4 开始,您可以pathlib
像这样使用:
from pathlib import Path
import shutil
for file in Path("C:\Users\vucin\Desktop\YouTube Download").glob("*.mp3"):
new_path = str(file.resolve()).replace("YouTube Download", "Muzika")
shutil.move(file, new_path)
与Path
结合使用,您可以使用通配符glob
搜索具有特定模式(例如,扩展名)的所有文件。*
由于您的新目标路径与源路径稍有偏差,您可以使用它replace
来指定新路径。要了解更多信息,pathlib
请参阅文档。
推荐阅读
- c++ - 将多维数组作为 void * 传递给外部“C”函数
- python - Django Rest Framework 没有从我的数据库中检索数据
- sql - 规范化 - 清除 sql 列中重复的拼写错误值的最佳方法
- recaptcha - 获取请求的 Recaptcha v3 保护
- wordpress - 将自定义分类法添加到所有帖子页面
- amazon-cloudformation - 创建cloudformation资源倍增
- r - 如何将 ggplot 的字体更改为 Times New Roman(在 OS X 上)?
- c# - 异步调用后断点消失
- python - 字典创建代码。这里最有可能发生了什么?
- visual-c++ - UserCutCallback 为每个输出记录两次