简体   繁体   中英

Renaming .png files python

Beginner question:

I am trying to rename .png files using:

import os

os.rename('x.png','y.png')

The error I get is:

WindowsError: [Error 2] The system cannot find the file specified.

I am in the right directory, and so are the files.The strange this is, if I manually rename the file (for example to 'h.png') and use that variable name in the rename command, it does work.

I am confused...

Why don't you use the shutil module?

import shutil
shutil.move('x.png','y.png')

But, be careful it doesn't rename your file but cut it with another name.

It's most likely that you got the Can't find file error because 'x.png' isn't the absolute path.

Explicitly call path and os.path.join(path, filename) prior to calling the rename and it will work.

Try this:

os.rename(os.path.join(os.getcwd(), 'x.png'), 'y.png')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM