How to delete data from file in Python
Last Updated :
22 Apr, 2025
When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data.
For more on file handling, check out:
Let’s explore the various ways to delete data from files. Consider our sample file sample.txt, which contains the following data:
sample.txt fileUsing os.remove()
This method is used when you want to permanently delete the entire file from the file system. The os.remove() function checks if the file exists and then removes it. It's useful for file cleanup tasks or when the data is no longer needed. Note that this method cannot delete directories, only files.
Python
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
print("Deleted")
else:
print("Not found")
Output
Deleted
Explanation: This code checks if sample.txt exists. If it does, it deletes the file using os.remove() and prints "Deleted". If not, it prints "Not found". This prevents errors by ensuring the file is only deleted if it exists.
Using truncate()
truncate() method is used to clear all contents of a file without deleting the file itself. This is useful when you want to reuse the same file but start fresh with no data inside. The file is opened in read/write mode and truncate() cuts off all existing content.
Python
with open("sample.txt", "r+") as f:
f.seek(0)
f.truncate()
print("Cleared")
Output
Cleared
Using truncate()Explanation: This code opens sample.txt in read and write mode. It moves the file pointer to the beginning using seek(0) and then clears all its contents with truncate(). The file remains, but its data is erased.
Using filtering
This method helps when you want to remove specific lines or content from a file, while keeping the rest intact. You read all lines, filter out the ones you don't want and write the rest back to the same file. This approach is ideal for making precise edits to a file’s contents.
Python
file_path = r"C:\Users\GFG0578\Desktop\nw\sample.txt"
with open(file_path, "r+") as f:
lines = [line for line in f if line.strip() != "Used in tech fields."]
f.seek(0)
f.writelines(lines)
f.truncate()
print("Removed")
Output
Removed
Using filteringExplanation: This code filters out the line "Used in tech fields." from the file, rewrites the remaining lines and truncates extra data, removing only the targeted line while keeping the rest.
Using temporary file
This is a safe method to remove specific data from a file. You read the original file line by line and write only the necessary content to a temporary file. After filtering, the original file is replaced with the temp file. This avoids direct editing of the original file, reducing the risk of data corruption.
Python
import os
src = r"C:\Users\GFG0578\Desktop\nw\sample.txt"
temp = r"C:\Users\GFG0578\Desktop\nw\temp.txt"
with open(src, "r") as infile, open(temp, "w") as outfile:
for line in infile:
if "Used in tech fields." not in line:
outfile.write(line)
os.replace(temp, src)
print("file filtered")
Output
file filtered
Using temporary fileExplanation: This code filters out lines containing "Used in tech fields." by copying the remaining lines to a temporary file, then replaces the original file with the updated one.
Similar Reads
How to delete from a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it âserializesâ the object first before writing it to file. Pickling is a way to convert a python object (list, dic
3 min read
How to delete a CSV file in Python?
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
2 min read
How to Read from a File in Python
Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently.Example File: geeks.txtHello World Hello GeeksforGe
5 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.
2 min read
How To Read .Data Files In Python?
Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
4 min read
Delete pages from a PDF file in Python
In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the
4 min read
How to open and close a file in Python
There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Opening a file in Python There a
4 min read
How to remove brackets from text file in Python ?
Sometimes it becomes tough to remove brackets from the text file which is unnecessary to us. Hence, python can do this for us. In python, we can remove brackets with the help of regular expressions. Syntax: # import re module for using regular expression import re patn =  re.sub(pattern, repl, sent
3 min read
How to Automate Data Cleaning in Python?
In Data Science and Machine Learning, Data Cleaning plays an essential role. Data Cleaning is the process of retaining only the crucial information from the output so that only relevant features are sent as input to the machine learning model. It is a very crucial step in data science and it helps i
10 min read
Loading Different Data Files in Python
We are given different Data files and our task is to load all of them using Python. In this article, we will discuss how to load different data files in Python. Loading Different Data Files in PythonBelow, are the example of Loading Different Data Files in Python: Loading Plain Text Files Loading Im
2 min read