Open In App

How to delete data from file in Python

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

sample.txt file

Using 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
Output

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
Output

Using filtering

Explanation: 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
Output

Using temporary file

Explanation: 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.



Next Article

Similar Reads