本文介绍了当该文件已经存在时,python os.rename“"无法创建该文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

K ..我只是使用在这里找到的简单脚本:

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

我基本上需要将所有像Colon-21.mp3这样的文件转换为21.mp3.

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

但是我得到了错误CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS.如何解决这个问题?我正在使用Windows 7.

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

推荐答案

问题就在这里:

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

Python索引从0开始,字符串"colon-"仅6个字符长,因此使用您的代码,冒号21.mp3将变为1.mp3.更改该行以使用filename[6:]代替,您的问题应该消失了.

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

这篇关于当该文件已经存在时,python os.rename“"无法创建该文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:50