繁体   English   中英

将特定文件类型从所有目录移动到一个文件夹的 Python 脚本

[英]Python script to move specific filetypes from the all directories to one folder

我正在尝试编写一个 python 脚本,将所有音乐文件从我的整个电脑移动到一个特定的文件夹。 它们到处都是,我想把它们都放在一个地方,所以我不想复制而是完全移动它们。

我已经能够使用此脚本列出所有文件:

import os

targetfiles = []
extensions = (".mp3", ".wav", ".flac")

for root, dirs, files in os.walk('/'):
    for file in files:
        if file.endswith(extensions):
            targetfiles.append(os.path.join(root, file))
print(targetfiles)

这会打印出所有文件的一个很好的列表,但我现在坚持要移动它们。

我用不同的代码做了很多不同的尝试,这是其中之一:

import os
import shutil

targetfiles = []
extensions = (".mp3", ".wav", ".flac")

for root, dirs, files in os.walk('/'):
    for file in files:
        if file.endswith(extensions):
            targetfiles.append(os.path.join(root, file))

new_path = 'C:/Users/Nicolaas/Music/All' + file
shutil.move(targetfiles, new_path)

但是我尝试的一切都给我一个错误:

TypeError: rename: src should be string, bytes or os.PathLike, not list

我想我已经达到了收集这一切的极限,因为我只是从 Python 开始,但如果有人能指出我正确的方向,我将不胜感激!

您正在尝试将文件列表移动到新位置,但shutil.move函数需要一个文件作为第一个参数。 targetfiles文件列表中的所有文件移动到新位置,您必须使用循环来单独移动每个文件。

for file in targetfiles:
    shutil.move(file, new_path)

如果需要,还可以在新路径'C:/Users/Nicolaas/Music/All/'中添加尾部斜杠

在旁注中,您确定移动具有这些扩展名的所有文件是个好主意吗? 我建议复制它们或进行备份。

编辑:您可以使用if语句从搜索中排除某些文件夹。

for root, dirs, files in os.walk('/'):
    if any(folder in root for folder in excluded_folders):
        continue
    for file in files:
        if file.endswith(extensions):
            targetfiles.append(os.path.join(root, file))

其中excluded_folder是不需要的文件夹的列表,例如: excluded_folders = ['Program Files', 'Windows']

我建议使用glob进行匹配:

import glob


def match(extension, root_dir):
    return glob.glob(f'**\\*.{extension}', root_dir=root_dir, recursive=True)


root_dirs = ['C:\\Path\\to\\Albums', 'C:\\Path\\to\\dir\\with\\music\\files']
excluded_folders = ['Bieber', 'Eminem']
extensions = ("mp3", "wav", "flac")

targetfiles = [f'{root_dir}\\{file_name}' for root_dir in root_dirs for extension in extensions for file_name in match(extension, root_dir) if not any(excluded_folder in file_name for excluded_folder in excluded_folders)]

然后你可以将这些文件移动到new_path

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM