使用 os.rename() Python 重命名 excel 文件

Max*_*Kim -2 python

我正在编写一个快速脚本,它将更改位于目录中的每个 excel 文件的名称:

[...]
for file_ in os.listdir(path):
   if 'Analytics Android' in file_:
      os.rename(file_, 'Android Orders.xlsx')
Run Code Online (Sandbox Code Playgroud)

但是,我收到一个错误:函数[Error 2] The system cannot find the file specified.不应该rename将名称更改为第二个参数吗?

orl*_*rlp 5

os.listdir 不提供绝对路径,而是列出给定路径的相对路径,因此您仍然必须创建完整路径:

for file_ in os.listdir(path):
    if 'Analytics Android' in file_:
        os.rename(os.path.join(path, file_), os.path.join(path, 'Android Orders.xlsx'))
Run Code Online (Sandbox Code Playgroud)