简体   繁体   English

组织文件时忽略文件夹

[英]Ignoring folders when organizing files

I am fairly new to python, and trying to write a program that organizes files based on their extensions我对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))

I want it to move files based on their extensions.我希望它根据扩展名移动文件 However, I am trying to figure out how to stop the folders from moving.但是,我想弄清楚如何阻止文件夹移动。 Any help would be greatly appreciated.任何帮助将不胜感激。

Also, for some reason, not every file is being moved, even though they have the same extension.此外,由于某种原因,并非每个文件都被移动,即使它们具有相同的扩展名。

As with most path operations, I recommend using the pathlib module.与大多数路径操作一样,我建议使用pathlib模块。 Pathlib is available since Python 3.4 and has portable (multi platform), high-level API for file system operations. Pathlib 从 Python 3.4 开始可用,并具有可移植(多平台)、用于文件系统操作的高级 API。

I recommend using the following methods on Path objects, to determine their type:我建议在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)

See here这里

In particular, the os.walk command .特别是os.walk命令 This command returns a 3-tuple with the dirpath, dirname, and filename.此命令返回一个包含目录路径、目录名和文件名的 3 元组。

In your case, you should use [x[0] for x in os.walk(dirname)]在你的情况下,你应该使用[x[0] for x in os.walk(dirname)]

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

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