问题
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