The rename method of the os module
The rename method renames and/or moves a file or folder. In the first parameter of the method we specify the original path to the file or folder, in the second parameter - the new path or file name/folders. In the second and third optional parameters, we can specify the file descriptor of the source and destination paths, respectively. The method returns None. If the file we want to rename does not exist, the method returns the exception FileNotFoundError.
Syntax
import os
os.rename(original path, new path, [source path file descriptor], [file descriptor of the new path])
Example
Let's rename the folder dir1:
import os
os.rename('dir1', 'dir2')
Example
Now let's rename the file:
import os
os.rename('file1.txt', 'file2.txt')
See also
-
method
makedirsof moduleos,
which creates a directory -
method
removeof moduleos,
which deletes the file -
method
getcwdmoduleos,
which returns the current working directory -
method
listdirof moduleos,
which returns a list of files in the working directory -
method
path.isdirof moduleos,
which checks the existence of a folder -
method
path.isfileof moduleos,
which checks the existence of a file