深度阅读

How to rename a file in Python using os.rename()?

作者
作者
2023年08月22日
更新时间
8.42 分钟
阅读时间
0
阅读量

To rename a file in Python, you can use the os.rename() method from the os library. This method takes the current name and new name of the file as its inputs and renames the file. Here’s an example:

import os

old_name = "/path/to/current_file_name.txt"
new_name = "/path/to/new_file_name.txt"
os.rename(old_name, new_name)

This example renames the file located at /path/to/current_file_name.txt to /path/to/new_file_name.txt using os.rename().

Note that if the new name already exists, os.rename() will overwrite it without warning. Also, if an exception occurs during the rename operation, the file may be left in an inconsistent state.

Using os.rename() is useful when you need to rename a file, such as when you want to change the name of a file to better reflect its contents or to avoid naming conflicts.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。