组织文件时忽略文件夹

Ignoring folders when organizing files

我是 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))

我希望它根据扩展名移动 文件。但是,我想弄清楚如何阻止 文件夹 移动。任何帮助将不胜感激。

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

here

特别是 os.walk command。此命令 returns 一个包含目录路径、目录名和文件名的三元组。

在你的情况下,你应该使用 [x[0] for x in os.walk(dirname)]

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

我建议在 Path 对象上使用以下方法来确定它们的类型:

import shutil
from pathlib import Path


# Using class for nicer grouping of target directories
# Note that pathlib.Path enables Unix-like path construction, even on Windows
class TargetPaths:
    IMAGES = Path.home().joinpath("Documents/Downloads/Images")
    DOCUMENTS = Path.home().joinpath("Documents/Downloads/Documents")
    OTHER = Path.home().joinpath("Documents/Downloads/Else")
    __ALL__ = (IMAGES, DOCUMENTS, OTHER)


for target_dir in TargetPaths.__ALL__:
    if not target_dir.is_dir():
        target_dir.mkdir(exist_ok=True)


source_folder = Path.home().joinpath("Documents/Downloads")  # the location of the files we want to move
# Get absolute paths to the files in source_folder
# files is a generator (only usable once)
files = (path.absolute() for path in source_folder.iterdir() if path.is_file())


def move(source_path, target_dir):
    shutil.move(str(source_path), str(target_dir.joinpath(file.name))


for path in files:
    if path.suffix in ('.JPG', '.png', '.jpg'):
        move(path, TargetPaths.IMAGES)
    elif path.suffix in ('.pdf', '.pptx'):
        move(path, TargetPaths.DOCUMENTS)
    else:
        move(path, TargetPaths.OTHER)