简体   繁体   中英

python os.rename “”cannot create a file when that file already exists

K.. I'm just using a simple script I found here:

import os
from os import rename, listdir

print os.listdir(".")
for filename in os.listdir("."):
    if filename.startswith("colon-"):
        print filename
        os.rename(filename, filename[7:])

I need to basically take all files like colon-21.mp3 converted to 21.mp3.

But I get the error CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS. How does one solve this? I am using Windows 7.

The problem is right here:

os.rename(filename, filename[7:])

Python indices start at 0, and the string "colon-" is only 6 characters long, so colon-21.mp3 will become 1.mp3 using your code. Change that line to use filename[6:] instead and your problem should be gone.

That said, using a hard coded string length like you are doing is not a good idea. It is error prone for exactly the reasons we have discovered here (hard coded numbers like this are often called "magic numbers" because it is difficult to tell why they are set to a given length). A superior alternative would be the following:

os.rename(filename, filename.split('-')[1])

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