如何移动不同子目录中的文件?

how to move files in different sub-directories?

我有一个包含不同扩展名文件的目录,我必须将这些文件移动到“文件目录”内的文件夹(创建它们)中,我写了那个,但我需要帮助(第一个项目请温柔)

import os
import shutil

os.makedirs("C:\FileOrganizer\FileOrganizer\Files\Images")
os.makedirs("C:\FileOrganizer\FileOrganizer\Files\Text")
os.makedirs("C:\FileOrganizer\FileOrganizer\Files\Mp3")

src_fldr = "C:\FileOrganizer\FileOrganizer\Files"
fldr_img ="C:\FileOrganizer\FileOrganizer\Files\Images"
fldr_txt = "C:\FileOrganizer\FileOrganizer\Files\Text"
fldr_mp3 = "C:\FileOrganizer\FileOrganizer\Files\Mp3"

for file in os.listdir(src_fldr): 
    filename = os.fsdecode(file)
    if filename.endswith(".txt", ".otd"):
        shutil.move(src_fldr, fldr_txt)
    elif filename.endswith(".jpeg", ".jpg", ".png"):
        shutil.move(src_fldr, fldr_img)
    elif filename.endswith(".mp3"):
        shutil.move(src_fldr, fldr_mp3)
    else: 
        pass

您应该将源文件而不是源文件夹移动到目标文件夹

for file in os.listdir(src_fldr): 
    filename = os.fsdecode(file) # remove me
    if filename.endswith(".txt", ".otd"):
        shutil.move(file, fldr_txt)
    elif filename.endswith(".jpeg", ".jpg", ".png"):
        shutil.move(file, fldr_img)
    elif filename.endswith(".mp3"):
        shutil.move(file, fldr_mp3)
    else: 
        pass

另外,我认为你应该删除 os.fsdecode 整行并直接更改为 file

if file.endswith(".txt", ".otd"):