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

How to replace multiple file name in python?

(ANSWERED) 我想更改此目录中的文件名。让他们称他们为 ai01.aif, ab01.aif 为 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'
>>> 

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

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

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

os.chdir(path)

循环之前的某处,或使用

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

当前目录中没有名为 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))

我的错误=>

我不在目录中。所以而不是

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)