Python add prefix to file names inside a directory

I need to add a prefix to file names within a directory. Whenever I try to do it though, it tries to add the prefix to the beginning of the file path. That won’t work. I have a few hundred files that I need to change, and I’ve been stuck on this for a while. Have any ideas? Here’s the closest I’ve come to getting it to work. I found this idea in this thread: How to add prefix to the files while unzipping in Python? If I could make this work inside my for loop to download and extract the files that would be cool, but it’s okay if this happens outside of that loop.

import os
import glob
import pathlib

for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
    dst = f"County_{file}"
    os.rename(file, os.path.join(file, dst))

That produces this error:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg' -> 'C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg\\County_C:\\Users\\UserName\\Desktop\\Wells\\Alcona_WaterWells.cpg'

I’d like to add "County_" to each file. The targeted files use this syntax: CountyName_WaterWells.ext

>Solution :

os.path.basename gets the file name, os.path.dirname gets directory names. Note that these may break if your slashes are in a weird direction. Putting them in your code, it would work like this

import os
import glob
import pathlib

for file in pathlib.Path(r'C:\Users\UserName\Desktop\Wells').glob("*WaterWells.*"):
    dst = f"County_{os.path.basename(file)}"
    os.rename(file, os.path.join(os.path.dirname(file), dst))

Leave a Reply