Python Forum

Full Version: rename files in a folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I'm trying to rename about 25 files in a directory. If I have a directory that has a bunch of .jpg's that have the start out, "scanXXX", I'd like to change the name to "356EXXX".

Here is what I've researched from the lovely internets,
###rename files 0601
import os, sys
###
def main():

    for count, filename in enumerate(os.listdir("C:\PG2")):
        dst ="356E" + str(count) + ".jpg"
        src ='PG2' + filename
        dst ='PG2' + dst

        os.rename(src, dst)

if __name__ == '__main__':

    main()
Here is my error message:
Error:
===================================== RESTART: C:/PG2/rename.py ===================================== Traceback (most recent call last): File "C:/PG2/rename.py", line 15, in <module> main() File "C:/PG2/rename.py", line 11, in main os.rename(src, dst) FileNotFoundError: [WinError 2] The system cannot find the file specified: 'PG2356E2-26.jpg' -> 'PG2356E0.jpg' >>>
Could this be a permissions issue? I've noticed on WIN10 that if you're not elevated, half the time scripts ain't workin'.

Thanks for any help,
windows10 home, hp pavilion
Take a close look at the filename error:

Error:
The system cannot find the file specified: 'PG2356E2-26.jpg'
You are intending to operate on a path name (like "C:\PG2\356E2-26.jpg"), but are instead handing to rename() a string with all that mushed together. You didn't put any path separators in. You could do that manually, but better is to use os.path functions to form them.

dir = "C:\PG2"
for count, filename in enumerate(os.listdir(dir)):
    dst = os.path.join(dir, f"356E{count}.jpg")
    src = os.path.join(dir, filename)

    os.rename(src, dst)
[...]
@bowlofred,
Many thanks. That did the trick.

I don't use os.path that much. I will start to incorporate.

Thanks again.