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

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Build a Credit Default Risk Prediction Model with LightGBM
In this Machine Learning Project, you will build a classification model for default prediction with LightGBM.

Deploying Machine Learning Models with Flask for Beginners
In this MLOps on GCP project you will learn to deploy a sales forecasting ML Model using Flask.

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.

Build a Multi ClassText Classification Model using Naive Bayes
Implement the Naive Bayes Algorithm to build a multi class text classification model in Python.

Azure Deep Learning-Deploy RNN CNN models for TimeSeries
In this Azure MLOps Project, you will learn to perform docker-based deployment of RNN and CNN Models for Time Series Forecasting on Azure Cloud.

Learn to Build a Siamese Neural Network for Image Similarity
In this Deep Learning Project, you will learn how to build a siamese neural network with Keras and Tensorflow for Image Similarity.

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

Many-to-One LSTM for Sentiment Analysis and Text Generation
In this LSTM Project , you will build develop a sentiment detection model using many-to-one LSTMs for accurate prediction of sentiment labels in airline text reviews. Additionally, we will also train many-to-one LSTMs on 'Alice's Adventures in Wonderland' to generate contextually relevant text.