Skip to main content
 首页 » 编程设计

python之在python中重命名单个文件

2025年05月04日27haluo1

我正在尝试重命名音频文件,但我一直收到 OSError: [Errno 2] No such file or directory。

在我的程序中,每个用户都有一个存放用户文件的目录。我通过执行以下操作获取每个用户的路径:

current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username) 
 
/Users/johnsmith/Documents/pythonprojects/project/files/john 

现在我想获取要重命名的现有文件的路径:

current_file_path = os.path.join(current_user_path,form.currentTitle.data) 
 
/Users/johnsmith/Documents/pythonprojects/project/files/john/File1 

重命名文件的路径为:

new_file_path = os.path.join(current_user_path, form.newTitle.data) 
 
/Users/johnsmith/Documents/pythonprojects/project/files/john/One 

现在我只是运行重命名命令:

os.rename(current_file_path, new_file_path) 

请您参考如下方法:

你可以使用os.rename用于重命名单个文件。

避免

OSError: [Errno 2] No such file or directory. 

检查文件是否存在

这是工作示例:

import os 
 
src = "D:/test/Untitled003.wav" 
dst = "D:/test/Audio001.wav" 
 
if os.path.isfile(src): 
    os.rename(src, dst)