You can use the "os.rename()" function to rename files in Python. The steps are: 1. Import os; 2. Set the original file variable name "old_name"; 3. Set the new file variable Named "new_name"; 4. Use "os.rename(old_name,new_name)" to rename.
# Operating system for this tutorial: Windows 10 system, Dell G3 computer.
In Python, you can use the os.rename() function to rename files. Here is a simple example:
import os # 原始文件名 old_name = 'old_file.txt' # 新文件名 new_name = 'new_file.txt' # 重命名文件 os.rename(old_name, new_name)
In the above example, we call os.rename() by specifying the original file name old_name and the new file name new_name function to rename files. This will rename old_file.txt to new_file.txt.
Please note that when the os.rename() function renames a file, it will overwrite the target file (if it exists). Therefore, make sure that the new filename does not duplicate an existing filename to avoid accidental overwrites or errors.
In addition, you can also use the shutil.move() function to implement file renaming, which provides more flexibility and functionality. Below is an example of shutil.move():
import shutil # 原始文件路径 old_path = '/path/to/old_file.txt' # 新文件路径 new_path = '/path/to/new_file.txt' # 重命名文件 shutil.move(old_path, new_path)
In this example, we use shutil.move() function to move and rename files by specifying The original file path old_path and the new file path new_path are used to complete the renaming operation.
The above is the detailed content of How to rename files in python. For more information, please follow other related articles on the PHP Chinese website!