Course
Renaming and Deleting Files
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module, you need to import it first and then you can call any related functions.
rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is an example to rename an existing file "
test1.txt
" to "test2.txt
"#!/usr/bin/python3import os# Rename a file from test1.txt to test2.txtos.rename( "test1.txt", "test2.txt" )
remove() Method
You can use the
remove()
method to delete files by supplying the name of the file to be deleted as the argument.Syntax
os.remove(file_name)
Example
Following is an example to delete an existing file "
test2.txt
"#!/usr/bin/python3import os# Delete file test2.txtos.remove("text2.txt")
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.