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

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Text Classification with Transformers-RoBERTa and XLNet Model
In this machine learning project, you will learn how to load, fine tune and evaluate various transformer models for text classification tasks.

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

AWS Project to Build and Deploy LSTM Model with Sagemaker
In this AWS Sagemaker Project, you will learn to build a LSTM model on Sagemaker for sales forecasting while analyzing the impact of weather conditions on Sales.

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.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

ML Model Deployment on AWS for Customer Churn Prediction
MLOps Project-Deploy Machine Learning Model to Production Python on AWS for Customer Churn Prediction

Build a Face Recognition System in Python using FaceNet
In this deep learning project, you will build your own face recognition system in Python using OpenCV and FaceNet by extracting features from an image of a person's face.

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.