简体   繁体   English

python os.rename“”在该文件已存在时无法创建该文件

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

K.. I'm just using a simple script I found here: K ..我只是使用在这里找到的简单脚本:

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. 我基本上需要将所有像Colon-21.mp3这样的文件转换为21.mp3。

But I get the error CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS. 但是我收到错误消息: CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS.无法CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS. How does one solve this? 如何解决这个问题? I am using Windows 7. 我正在使用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. Python索引从0开始,字符串"colon-"只有6个字符长,因此使用您的代码,冒号21.mp3将变为1.mp3。 Change that line to use filename[6:] instead and your problem should be gone. 更改该行以使用filename[6:]代替,您的问题应该消失了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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