Use the os.Rename function to rename files or directories
File renaming is one of the operations often encountered in daily development. In Python, we can use the Rename function of the os module to rename files or directories. This article will introduce how to use the os.Rename function to rename files or directories through simple code examples.
First, we need to import the os module in order to use the Rename function in it. The code is as follows:
import os
Then, we can use the os.Rename function to rename the file. The following is a sample code:
import os # 原文件名 old_filename = "old_file.txt" # 新文件名 new_filename = "new_file.txt" # 重命名文件 os.rename(old_filename, new_filename)
In the above code, we define an original file name and a new file name, and then use the os.rename function to rename the file to the new file name. When using this function, you need to pass in two parameters, namely the original file name and the new file name.
In addition to renaming files, we can also use the os.Rename function to rename directories. The following is a sample code:
import os # 原目录名 old_dirname = "old_dir" # 新目录名 new_dirname = "new_dir" # 重命名目录 os.rename(old_dirname, new_dirname)
In the above code, we define an original directory name and a new directory name, and then use the os.rename function to rename the directory to the new directory name. Similarly, when using this function, you need to pass in two parameters, namely the original directory name and the new directory name.
It should be noted that when using the os.Rename function to perform a rename operation, you must ensure that the original file or directory exists, and the new file or directory name cannot be the same as other existing files or directories. Otherwise, a FileNotFoundError or FileExistsError exception will be raised.
In addition to using the os.Rename function, we can also use the move function of the shutil module to rename files or directories. The usage of this function is similar to the os.Rename function, but it can handle more complex operations, such as moving files, copying files, etc. However, it should be noted that the shutil module is a high-level module that encapsulates more low-level operations and is relatively more complex.
To sum up, we can rename files or directories by using the os.Rename function. Whether it is a file or a directory, just pass the original name and new name as parameters to the function. I hope this article will be helpful to you when dealing with file or directory renaming in daily development.
The above is the detailed content of Use the os.Rename function to rename a file or directory. For more information, please follow other related articles on the PHP Chinese website!