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

China☆狼群 提交于 2019-12-24 16:58:20

问题


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.


回答1:


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])


来源:https://stackoverflow.com/questions/13540241/python-os-rename-cannot-create-a-file-when-that-file-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!