How to Clear a Text File in Python

While programs are often used to create files, there are times when programmers also need to erase file data. Luckily, there are multiple ways to clear text from a file. In this post, we’ll use some simple examples to demonstrate how to clear a text file in Python.

By making use of some of Python’s standard tools, we can open, read, and clear text files. We’ll also learn how to remove specific lines from a text file using slice notation.

Python simplifies the process of file handling, resulting in more succinct programs. As a result of studying this guide, you’ll understand how Python can clear text files and delete lines of data.

Clear a Text File Using the open() Function in write Mode

Opening a file in write mode will automatically delete the file’s contents. The open() function takes two arguments, the text file we’d like to open and the mode we’re opening it in.

Opening a file in write mode clears its data. Also, if the file specified doesn’t exist, Python will create a new one. The simplest way to delete a file is to use open() and assign it to a new variable in write mode.

file_to_delete = open("info.txt",'w')
file_to_delete.close()

The Python with statement simplifies exception handling. Using with to open a file in write mode will also clear its data. A pass statement completes the example.

# clear the data in the info file
with open("info.txt",'w') as file:
    pass

How to Clear a File with the truncate() Method

The truncate() method reduces a document’s size. This method takes an optional argument that sets the new size of the file. If no argument is supplied, the file is left unchanged.

An attempt to truncate a file to longer than its original size may have unexpected results. For example, the program may add white space to the end of the file if the truncate size exceeds the original file size.

We’ll use a demo text file to test Python’s capabilities for truncating files:

info.txt
Guido van Rossum created Python in 1991.
Python is a general purpose programming language.
One of Python’s strengths is readability.

with open("info.txt",'r+') as file:
    file.truncate(16)

# read the file’s contents
with open("info.txt", 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line)

Output

Guido van Rossum

In the above example, the truncate() method reduced the file to the first 16 characters of text. Notice that we opened the file in both read and write mode. This is necessary in order for the truncate method to work.

By passing a value of 0 to the truncate() method, it’s possible to clear the text file completely.

with open("example.txt",'r+') as file:
    file.truncate(0)

The above Python code will clear a text file of it’s content. Using the truncate() method in this manner will reduce the file size to 0, erasing any content the file contained.

Clear a Text File Using Python List Slicing

With Python slice notation, it’s possible to retrieve a subset of a list, string, or tuple. Using this Python feature, we can define the start and end indexes of a given subset.

Slice notation uses a special syntax to find a subset of a range of values. The following example shows how slice notification works. By defining the start, end, and step of the slice, we’ll obtain a subset of the original list.

nums = [1,2,3,4,5,6,7,8,9]
sub = nums[1:8:2]
print(sub)

Output

[2, 4, 6, 8]

Next, we’ll use the same info.txt document from the previous section to demonstrate how slice notation can be used to clear lines from a text file. The readlines() method will return a list of the lines of text in the document.

After the lines are extracted, we can use slice notation to create a new list that we’ll use to overwrite the old file. Only the first line of text will remain. The others will be cleared from the text file.

# read the file's contents
read_file = open("info.txt",'r')
lines = read_file.readlines()
read_file.close()

write_file = open("info.txt",'w')

# slice the file's content
lines = lines[:1]

for line in lines:
    write_file.write(line)
    print(line)

write_file.close()

Output

Guido van Rossum created Python in 1991.

How to Delete Specific Lines from a Text File

Using some common Python functions, we can also clear specific lines of data from text files. It’s especially helpful if we know which lines we want to remove ahead of time. In that case, we can use slice notation to retrieve a subset of the file.

By writing over a file with a subset of its data, we can remove lines of text. The following examples use an excerpt from the poem “Dream Deferred” by the American writer Langston Hughes.

dream.txt
What happens to a dream deferred?
Does it dry up
Like a raisin in the sun?

Clear the First Line of a Text File

In order to clear the first line of text from a file, we’ll need to use a few of Python’s file handling methods. Firstly, we’ll use readlines() to get a list of the file’s text data. With the seek() method, we can manually reposition the file pointer.

Secondly, we can use the truncate() method to resize the file. Thirdly, we’ll write a new list of lines to the file. Using slice notation, it’s possible to omit the first line of the original file.

with open("dream.txt",'r+') as file:
    # read the lines
    lines = file.readlines()

    # move to the top of the file
    file.seek(0)
    file.truncate()

    file.writelines(lines[1:])

with open("dream.txt",'r') as file:
    lines = file.readlines()

for line in lines:
    print(line)

Output

Does it dry up

Like a raisin in the sun?

Clear Multiple Lines from a Text File

It’s also possible to remove more than one line of text from a file. With slice notation, we can create any subset of the data we want. Using this method of overwriting the original file, we can effectively clear the file of any unwanted data.

By changing the start and end indexes of the slice, we’ll get a different subset of the dream.txt file. It’s also possible to combine sliced ​​lists. Using these tools offers plenty of versatility when it comes to creating subsets of lists.

with open("dream.txt",'r+') as file:
    # read the lines
    lines = file.readlines()

    # move to the top of the file
    file.seek(0)
    file.truncate()

    file.writelines(lines[:3])

with open("dream.txt",'r') as file:
    lines = file.readlines()

for line in lines:
    print(line)

Output

What happens to a dream deferred?

How to Clear a Text File Using a String

What if we want to remove a line from a string that contains a certain word, phrase, or number? We can use a Python if statement to check the string data of each line. If the string we’re looking for is in the line, we can avoid including it in the output file.

employee.txt
Name: Jamie Jameson
Age: 37
Occupation: Copywriter
Starting Date: April 3, 2019

In this example, we need to open the file three times. To begin, we’ll open the file to extract its contents. Next, we’ll write the data to a new file, clearing the lines we don’t want. Lastly, we’ll need to open the file and read it to prove that the file was handled correctly.

data_file  = open("employee.txt",'r')
lines = data_file.readlines()
data_file.close()

write_file = open("employee.txt",'w')
for line in lines:
    if "Age" not in line:
        write_file.write(line)

write_file.close()

read_file = open("employee.txt",'r')
lines = read_file.readlines()
read_file.close()

for line in lines:
    print(line)

Output

Name: James Jameson

Occupation: Copywriter

Starting Date: April 3, 2019

Summary

In this post we’ve taken an in-depth look at how to clear text files in Python. We’ve seen that the Python language offers many options for doing this task. Using some of the methods and functions that come standard with every install of Python, we are able to clear entire files as well remove specific lines from a file.

While tools like slice notation are great for clearing text files, they come in handy in other areas too. In this way, each new feature of Python that you study will improve your overall coding abilities.

Related Posts

If you found this helpful post and would like to learn more about programming with Python, follow these links to more great articles from our team at Python For Beginners. Whether it’s file handling and data management, you’ll learn the skills needed to thrive in today’s rapidly changing, digital world.

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Leave a Comment