- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Renaming and Deleting Files in Python
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.
The 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 the example to rename an existing file test1.txt −
#!/usr/bin/python import os # Rename a file from test1.txt to test2.txt os.rename( "test1.txt", "test2.txt" )
The 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 the example to delete an existing file test2.txt −
#!/usr/bin/python import os # Delete file test2.txt os.remove("text2.txt")
- Related Articles
- How to Protect Files and Directories from Deleting in Linux
- Renaming column names – Python Pandas
- PHP: Unlink All Files Within A Directory, and then Deleting That Directory
- Renaming imports and exports in JavaScript
- Python - Renaming the columns of Pandas DataFrame
- Opening and Closing Files in Python
- Reading and Writing Files in Python
- Deleting a Label in Python Tkinter
- What is Register Renaming?
- Listing out directories and files in Python?
- Reading and Writing to text files in Python
- Renaming column name in a MongoDB collection?
- Generate temporary files and directories using Python
- Encode and decode uuencode files using Python
- Writing files in background in Python

Advertisements