ID : 411
viewed : 158
Tags : PythonPython File
99
If you wish to rename a file in Python, choose one of the following options.
os.rename()
to rename a file.shutil.move()
to rename a file.os.rename()
The function os.rename()
can be used to rename a file in Python.
For example,
import os file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt") file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension") os.rename(file_oldname, file_newname_newfile)
In the above example,
file_oldname
- the old file name.
file_newname_newfile
- the new file name.
Result:
file_oldname
is renamed to file_newname_newfile
file_oldname
will be found in file_newname_newfile
.Pre-requisites:
os
module.import os
If the source/destination file doesn’t exist in the current directory where the code is executed, mention the absolute or relative path to the files.
[WinError 2] The system cannot find the file specified
[WinError 183] Cannot create a file when that file already exists
shutil.move()
The function shutil.move()
can also be used to rename a file in Python.
For example,
import shutil file_oldname = os.path.join("c:\\Folder-1", "OldFileName.txt") file_newname_newfile = os.path.join("c:\\Folder-1", "NewFileName.NewExtension") newFileName=shutil.move(file_oldname, file_newname_newfile) print ("The renamed file has the name:",newFileName)
In the above example,
file_oldname
: the old file name.
file_newname_newfile
: the new file name.
Result:
file_oldname
is renamed to file_newname_newfile
file_oldname
will now be found in file_newname_newfile
.newFileName
, which is the new file name.Pre-requisites:
shutil
module as,import shutil
If the source/destination file doesn’t exist in the current directory where the code is executed, mention the absolute or relative path to the files.
[WinError 2] The system cannot find the file specified.