Renaming and Deleting Files in Python: File Manipulation

thumb_up 1  ·  sell Python file renaming, Renaming files in Python, 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.

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/python3 import os # Rename a file from test1.txt to test2.txt os.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/python3 import os # Delete file test2.txt os.remove("text2.txt")
 
 
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
 

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back