Search code examples
pythonpython-3.xrenamefile-rename

Renaming file in Python


I'm trying to rename the files in a folder, but I can't. This is my code:

import os

directory = r"C:\Users\jhonatta-silva\Downloads"

for file in os.listdir(directory):
    if file.startswith("PBI"):
        os.rename(file, file.strip("0123456789 "))

and I receive an error like this:

[WinError 2] The system cannot find the file specified: 'PBIItemsResults132.csv' -> 'PBIItemsResults132.csv'

Solution

  • You have to add the directory to the names in the os.rename() call.

    import os
    
    directory = r"C:\Users\jhonatta-silva\Downloads"
    
    for file in os.listdir(directory):
        if file.startswith("PBI"):
            os.rename(os.path.join(directory, file), os.path.join(file.strip("0123456789 ")))
    

    Instead of using os.listdir() and then file.startswith(), you can use glob.glob() to just process files beginning with that prefix. It returns full paths when the argument is a full path.

    import os, glob
    
    directory = r"C:\Users\jhonatta-silva\Downloads"
    
    for file in glob.glob(os.path.join(directory, "PBI*")):
        os.rename(file, file.rstrip("0123456789 "))