jamesdeluk
jamesdeluk

Reputation: 324

Python: Rename directories with subdirectories

I've read a few other posts and tried the code in those answers but can't get mine to work.

This is my file structure:

motherfile g934uth98t
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile g934uth98t/big bad wolf r6b5n656n

The goal is:

motherfile
motherfile/kid file
motherfile/kid file/something elsee goes here
motherfile/big bad wolf

This is my code:

for root, dirs, files in os.walk(".", topdown=True):
    for name in dirs:
        direc = os.path.join(root, name)
        newdirec = '.'
        for part in direc.split('\\')[1:]:
            newdirec += '\\'
            newdirec += ' '.join(part.split()[:-1])
        os.rename(direc,newdirec)

Without the os.rename, and using prints (direc then newdirec), it works fine.

motherfile g934uth98t
motherfile
motherfile g934uth98t/kid file fh984bvt34ynt
motherfile/kid file
motherfile g934uth98t/kid file fh984bvt34ynt/something elsee goes here 98573v4985hy4
motherfile/kid file/something elsee goes here
motherfile g934uth98t/big bad wolf r6b5n656n
motherfile/big bad wolf

However, when it renames, it does the motherfile, but then all the other directories no longer exist (as they're relative to motherfile g934uth98t), so the script ends.

With topdown=False, I get an error: FileNotFoundError: [WinError 3] The system cannot find the path specified: '.\\motherfile g934uth98t\\kid file fh984bvt34ynt\\something elsee goes here 98573v4985hy4' -> '.\\motherfile\\kid file\\something elsee goes here'

How can I fix this?

EDIT: Tried this, still no luck, same error (second one). Perhaps it's a Windows file directory format issue?

import os

originaldirs = []
count = 0

def collect():
    global originaldirs
    originaldirs = []
    for root, dirs, files in os.walk(".", topdown=False):
        for name in dirs:
            originaldirs.append(os.path.join(root, name))
    global count
    count += 1

def rename_first():
    target = originaldirs[count]
    print(target)
    newdirec = '.'
    for part in target.split('\\')[1:]:
        newdirec += '\\'
        newdirec += ' '.join(part.split()[:-1])
        newdirec.replace('\\','//')
    # os.rename(target,newdirec)
    print(newdirec)

while True:
    try:
        collect()
        rename_first()
    except IndexError:
        print('Fin')
        break

Upvotes: 0

Views: 110

Answers (1)

Szabolcs
Szabolcs

Reputation: 4086

Try this:

from pathlib import Path

for path in Path(".").glob("**/*"):
    if path.is_dir():
        target = path.parent / " ".join(path.name.split()[:-1]) 
        path.rename(target)

Upvotes: 1

Related Questions