如何在python中替换多个文件名?

时间:2016-01-04 21:02:25

标签: python python-3.x dir

(ANSWERED)我想从这个目录中更改文件名。我们称之为ai01.aif,ab01.aif to changedai01.aif,changedab01.aif。

import os, sys

path="/Users/Stephane/Desktop/AudioFiles"
dirs=os.listdir(os.path.expanduser(path))
i="changed"

for file in dirs:
    newname=i+file
    os.rename(file,newname)

我收到了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'ai01.aif' -> 'changedai01.aif'
>>> 

4 个答案:

答案 0 :(得分:3)

当前目录中没有名为ai01.aif的文件(这通常是您的脚本所在的文件,但可能位于其他位置)。您获取内容的目录不是当前目录。您需要将您正在使用的目录添加到文件名的开头。

import os, sys

path = os.path.expanduser("/Users/Stephane/Desktop/AudioFiles")
dirs = os.listdir(path)
i    = "changed"

for file in dirs:
    newname = i + file
    os.rename(os.path.join(path, file), os.path.join(path, newname))

答案 1 :(得分:2)

您需要在重命名或使用全名之前切换到路径,因此请添加

os.chdir(path)

在循环之前的某个地方,或者使用

os.rename(os.path.join(path, newname), os.path.join(path, file))

答案 2 :(得分:1)

您需要文件的绝对路径,请在此处使用join:

file_path = os.path.join(path, file)

答案 3 :(得分:1)

我的错误=&gt;

我不在目录中。而不是

import os, sys

path="/Users/Stephane/Desktop/AudioFiles"
dirs=os.listdir(os.path.expanduser(path))
i="changed"

for file in dirs:
    newname=i+file
    os.rename(file,newname)

应该是:

import os, sys

path="/Users/Stephane/Desktop/AudioFiles"
dirs=os.listdir(os.path.expanduser(path))
i="changed"

for file in dirs:
    newname=i+file

我的错误在那里

    os.rename(path+"/"+file, path+"/"+newname)