首页 > 解决方案 > 如何遍历文件夹中的文件以移动具有特定扩展名的每个文件

问题描述

我复制了一个用于下载 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()

标签: pythonfilescripting

解决方案


从 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请参阅文档


推荐阅读