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

2024-10-16 22:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

(回答)我想更改此目录中的文件名。叫它们ai01.aif,ab01.aif来更改dai01.aif,更改dab01.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'
>>> 

Tags: pathinimport目录os文件名sysfile
3条回答

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

os.chdir(path)

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

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

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

file_path = 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))

相关问题 更多 >