Iacopo Passeri
Iacopo Passeri

Reputation: 145

Python: how to move a file with a certain name to a folder with the same name

I have a situation in which the directory I'm working at has many files and folders (something like that):

AAA_SUBFOLDER
AAA_FILE_1
AAA_FILE_2
BBB_SUBFOLDER
BBB_FILE_1
BBB_FILE_2

So files and subfolders both starting with AAA or BBB(and so on with CCC, DDD..). What I'd like to do is a python script that moves all the AAA files to the AAA subfolder and iterate this for all the files and subfolders with the same names in order to obtain something like this:

AAA_SUBFOLDER
  - AAA_FILE_1
  - AAA_FILE_2
BBB_SUBFOLDER
  - BBB_FILE_1
  - BBB_FILE_2
...

Can you help me? Thanks in advance!

Upvotes: 0

Views: 2136

Answers (2)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15558

This is my solution using pathlib rename ;) The script as it is assume the current is the path with your files and folders.

# using pathlip
from collections import defaultdict
from pathlib import Path

TARGET_DIR = Path('.') # script dir

FILES_AND_FOLDERS = TARGET_DIR.rglob('*')

# storage with files and folders 
storage = defaultdict(list)
for blob in FILES_AND_FOLDERS:
    if blob.is_file():
        storage['files'].append(blob)
    elif blob.is_dir():
        storage['dir'].append(blob)

# for each dir check if file first 3 characters 
# match if so move by rename
    
for directory in storage['dir']:
    for file in storage['files']:
        if file.name[:3] == directory.name[:3]:
            file.rename(directory / file)
    
# you can look at shutil too

Upvotes: 0

Beygel
Beygel

Reputation: 113

this solution should work for your requirement. steps:

  1. make sure you have python installed
  2. save script to a file (lets say main.py)
  3. run the saved file with 2 arguments - 1 for path you want to organize, 2 for the delimiter of the subfolder. example: python main.py -p "D:\path\to\files" -d "_"

!! this doesn't rearrange inner folders, only top level.

if you got any questions, I'll gladly help.

import os
import argparse
from pathlib import Path

def parse_args() -> tuple:
    ap = argparse.ArgumentParser()
    ap.add_argument("-p", "--path", default="./files", help="path to the folder that needs organizing")
    ap.add_argument("-d", "--delimiter", default="_", help="delimiter of file names")
    return ap.parse_args()

args = parse_args()

for filename in os.listdir(args.path):
    file_path = os.path.join(args.path, filename)
    if not os.path.isfile(file_path):
        continue
    subfolder_name = Path(filename).stem.split(args.delimiter)[0]
    subfolder_path = os.path.join(args.path,subfolder_name)
    os.makedirs(subfolder_path, exist_ok=True)
    os.rename(file_path, os.path.join(subfolder_path, filename))


Upvotes: 1

Related Questions