Python 组织文件时忽略文件夹

Python 组织文件时忽略文件夹,python,organization,Python,Organization,我是python的新手,正在尝试编写一个基于扩展名组织文件的程序 import os import shutil newpath1 = r'C:\Users\User1\Documents\Downloads\Images' if not os.path.exists(newpath1): # check to see if they already exist os.makedirs(newpath1) newpath2 = r'C:\User

我是python的新手,正在尝试编写一个基于扩展名组织文件的程序

import os
import shutil

newpath1 = r'C:\Users\User1\Documents\Downloads\Images'
if not os.path.exists(newpath1):                     # check to see if they already exist
    os.makedirs(newpath1)
newpath2 = r'C:\Users\User1\Documents\Downloads\Documents'
if not os.path.exists(newpath2):
    os.makedirs(newpath2)
newpath3 = r'C:\Users\User1\Documents\Downloads\Else'
if not os.path.exists(newpath3):
    os.makedirs(newpath3)

source_folder = r"C:\Users\User1\Documents\Downloads" # the location of the files we want to move
files = os.listdir(source_folder)

for file in files:
    if file.endswith(('.JPG', '.png', '.jpg')):
        shutil.move(os.path.join(source_folder,file), os.path.join(newpath1,file))
    elif file.endswith(('.pdf', '.pptx')):
        shutil.move(os.path.join(source_folder,file), os.path.join(newpath2,file))
    #elif file is folder:
        #do nothing
    else:
        shutil.move(os.path.join(source_folder,file), os.path.join(newpath3,file))
我希望它根据扩展名移动文件。但是,我正在试图找出如何阻止文件夹移动。任何帮助都将不胜感激

此外,由于某些原因,并非每个文件都在移动,即使它们具有相同的扩展名。

请参阅

特别是,
os.walk
。此命令返回一个包含dirpath、dirname和filename的三元组


在您的情况下,应该在os.walk(dirname)中为x使用
[x[0]

与大多数路径操作一样,我建议使用该模块。Pathlib从Python 3.4开始提供,并且具有用于文件系统操作的可移植(多平台)高级API

我建议对
Path
对象使用以下方法来确定其类型:

导入shutil
从pathlib导入路径
#使用类对目标目录进行更好的分组
#请注意,pathlib.Path支持类似Unix的路径构造,即使在Windows上也是如此
类目标路径:
IMAGES=Path.home().joinpath(“文档/下载/图像”)
DOCUMENTS=Path.home().joinpath(“文档/下载/文档”)
OTHER=Path.home().joinpath(“文档/下载/其他”)
__所有(图像、文档、其他)
对于TargetPaths中的target\u dir.\uuu ALL\uuu:
如果不是target_dir.is_dir():
target_dir.mkdir(exist_ok=True)
source_folder=Path.home().joinpath(“文档/下载”)#要移动的文件的位置
#获取源文件夹中文件的绝对路径
#文件是生成器(只能使用一次)
files=(path.absolute()表示源文件夹中的路径。如果path.is\u file(),则为iterdir())
def移动(源路径、目标目录):
move(str(source_path),str(target_dir.joinpath(file.name))
对于文件中的路径:
如果path.suffix出现在('.JPG'、'.png'、'.JPG'):
移动(路径、目标路径、图像)
('.pdf','.pptx')中的elif path.suffix:
移动(路径,TargetPaths.DOCUMENTS)
其他:
移动(路径、目标路径、其他)

<代码>如果有帮助,请考虑将答案标记为已接受。