How to Create and Delete Files in Python with Example?

This tutorial will guide you through the step-by-step how to create and delete files in Python with practical examples for mastering file handling. | ProjectPro

Have you tried to open, create or delete a file through python? Python provides convenient methods for handling files. Whether you're creating a new file or deleting an existing one, Python offers simple functions to make these tasks seamless. This tutorial will help you explore the step-by-step process of creating and deleting files in Python.

How to Create a File in Python? 

Python provides several methods to achieve this, and the following examples demonstrate the various approaches. Let’s explore one by one below - 

How to Create a Python File in Terminal? 

Creating a Python file in the terminal is a fundamental skill for developers. Follow these steps to create a Python file using terminal commands.

How to create a python file in terminal

After running this command, you can open the newly created file in your preferred text editor or integrated development environment (IDE) to start coding. 

How to Create a Python File with Open? 

Python's built-in open() function is a versatile tool for file manipulation, including file creation. Check below the example of creating a Python file using the open() function.

Python create file with Open

The above script will create a new Python file named 'new_python_file.py' in the current working directory or the specified path.

How to Create a Python File in a Directory? 

If you want to create a Python file in a specific directory, you can provide the path along with the file name. Ensure that the directory exists, or the script will raise an error.

Python create file in directory

Modify the directory_path variable with the path to your desired directory.

How to Check and Create a Python File if Not Exists? 

To prevent overwriting existing files, it's a good practice to check if the file exists before creating a new one. Here's an example demonstrating file creation only if it doesn't exist.

Python create file if not exists

This script uses the os.path.exists() method to check if the file exists before creating it.

How to Delete a File in Python? 

Deleting files in Python is equally straightforward. The os.remove() function allows you to remove a file, but ensuring the file exists is crucial before attempting deletion.

How to Delete a File in Python Using os.remove()?

Python delete file

The os.remove() function is used to delete a file in Python.

Example - Creation and Deletion of Files with Proper Example in Python

Here is a simple example to demonstrate the creation and deletion of files with proper example in python - 

Step 1 - Importing a Library

    import os

We have only imported os which is needed.

Step 2 - Creating a File

We created a file by function .write, and here, we have created a text file. Then, we wrote a statement in the file and closed the file.   

    with open("file.txt", "xt") as f:

        f.write("This is a New File. Just Created!")

        f.close()

Step 3 - Opening and Deleting File

We have open the file by using the .read function and closed the file by .close function. Finally, we have deleted the file by os.remove function. 

    with open("file.txt", "rt") as f:

        data = f.read()

        f.close()

    print(data)

    os.remove("file.txt")

So the output comes as 

This is a New File. Just Created!

Practice more Python Operations with ProjectPro!

If you want to get good at using Python, it's more than just reading and learning. You need to practice with real projects. That's where ProjectPro comes in. It offers a dynamic collection of 270 projects to try out. These projects are all about data science and big data, making learning fun and hands-on. So, instead of just reading about Python, why not play with it and make learning exciting? Check out ProjectPro Repository and see how much better you can become at Python by getting your hands dirty with real projects! 

Download Materials

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

Isolation Forest Model and LOF for Anomaly Detection in Python
Credit Card Fraud Detection Project - Build an Isolation Forest Model and Local Outlier Factor (LOF) in Python to identify fraudulent credit card transactions.

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

End-to-End Snowflake Healthcare Analytics Project on AWS-1
In this Snowflake Healthcare Analytics Project, you will leverage Snowflake on AWS to predict patient length of stay (LOS) in hospitals. The prediction of LOS can help in efficient resource allocation, lower the risk of staff/visitor infections, and improve overall hospital functioning.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

Abstractive Text Summarization using Transformers-BART Model
Deep Learning Project to implement an Abstractive Text Summarizer using Google's Transformers-BART Model to generate news article headlines.

Recommender System Machine Learning Project for Beginners-3
Content Based Recommender System Project - Building a Content-Based Product Recommender App with Streamlit