简体   繁体   中英

Ignoring folders when organizing files

I am fairly new to python, and trying to write a program that organizes files based on their extensions

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 is available since Python 3.4 and has portable (multi platform), high-level API for file system operations.

I recommend using the following methods on Path objects, to determine their type:

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 . This command returns a 3-tuple with the dirpath, dirname, and filename.

In your case, you should use [x[0] for x in os.walk(dirname)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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