How to change folder names in python?

You can write it out fairly straight-forward, using os.listdir and the os.path functions:

import os
basedir = 'C:/Test'
for fn in os.listdir(basedir):
  if not os.path.isdir(os.path.join(basedir, fn)):
    continue # Not a directory
  if ',' in fn:
    continue # Already in the correct form
  if ' ' not in fn:
    continue # Invalid format
  firstname,_,surname = fn.rpartition(' ')
  os.rename(os.path.join(basedir, fn),
            os.path.join(basedir, surname + ', ' + firstname))

An alternative to os.rename is shutil.move(src, dest)

import shutil
import os
shutil.move("M://source/folder", "M://destination/folder") 
os.rename("M://source/folder", "M://destination/folder")

Differences:

  1. OS module might fail to move a file if the source and destination path is on different file systems or drive. But shutil.move will not fail in this kind of cases.
  2. shutil.move checks if the source and destination path are on the same file system or not. But os.rename does not check, thus it fails sometimes.

  3. After checking the source and destination path, if it is found that they are not in the same file system, shutil.move will copy the file first to the destination. Then it will delete the file from the source file. Thus we can say shutil.move is a smarter method to move a file in Python when the source and destination path are not on the same drive or file system.

  4. shutil.move works on high-level functions, while os.rename works on lower-level functions.

I would also advise using pathlib to manipulate paths:

from shutil import move
from pathlib import Path


base_path = Path("C:/Test")

for folder in base_path.iterdir():
    if not folder.is_dir() or folder.name.startswith("."):
        continue

    name = folder.name
    new_name = ", ".join(name.split(" "))
    new_folder = folder.parent / new_name

    move(folder, new_folder)



You can just put it in one command, with the full paths.

import os
os.rename("/path/old_folder_name", "/path/new_folder_name")

os.rename("Joe Blow", "Blow, Joe")

Seems to work fine for me. Which part are you having trouble with?

Tags:

Python

Rename