Reputation: 145
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
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
Reputation: 113
this solution should work for your requirement. steps:
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