[Python] Using pathlib and shutil.move not moving file into subfolder that does exist

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    On MacOS I am looping through the source folder of pdf's and checking the destination folder if the there is an existing subfolder with the same name as the file. I am encountering a problem when I run the program it goes directly to my else statement even though the subfolder I know exists. I have tested this on Windows and it works fine but for some reason I can't get it to run successfully on mac. The only thing I can think of is because of the .DS_Store hidden file type that is hanging this up. Here's my existing code

    import shutil
    import os
    from pathlib import Path

    source = '/Users/miram/Library/CloudStorage/OneDrive-Company/Docs/Test_SRCDirectory'
    dest = '/MAIN/Building-D1D-RFS2'


    fileword_target = "CRATE"

    #File Rename
    for file in Path(source).iterdir():
    name = file.stem.split(fileword_target)[0].rstrip()
    subdir = Path(dest, name)
    print(f"Checking subdir: {subdir}")

    #Move file into folder that matches name variable
    if subdir.exists():
    destination = Path(subdir, file.name)
    shutil.move(file, destination)
    print(f"{name} have been moved.")
    else:
    print(f"Folder not found for {name}")


    my files I am moving look like this:


    filename L1 CRATE D1D
    ​

    which the .stem/.strip should give me my subfolder name that I am searching for in the destination folder.

    Continue reading...

Compartilhe esta Página