Clear File in Python

The quickest way to clear file contents in Python is by using the following code:

file = open("D:/my_file.txt","w")
file.close()

This code will open the file for writing and close it in the next line.

If there is no information entered, the file will erase contents and become empty, so there is no need for clearing the file before writing.

If there is no file, Python will create an empty text file.

This is the file we are going to use in the next examples:

Clear file if exists

If you don’t want Python to create a file if it doesn’t exist, you have to check whether the file is in the specified location before writing to a file.

try:
    test = open("D:/my_file.txt", "r")
    test.close()
    file = open("D:/my_file.txt", "w")
    file.close()
except IOError:
    print("There is no such file")

First, Python tries to open the file for reading. If it fails, it automatically returns an exception under except. If there is a file, it will be opened for reading and after that for writing.

The file is closed before anything is written to it, so all data inside the file is erased.

Clear file after reading

Now, let’s try to read the file and clear it after that.

file = open("D:/my_file.txt", "r")
lines = file.read().splitlines()
file.close()
file = open("D:/my_file.txt", "w")
file.close()

print(lines)

Each line inside the file is saved as a list element before clearing file contents.

The printed result is:

['First line', 'Second line', 'Third line']

Clear file line by line

You can also clear a file line by line:

file = open("D:/my_file.txt", "r")
lines = file.readlines()
file.close()

file = open("D:/my_file.txt", "w")
for line in lines:
    file.write("")

file.close()

First, this code reads lines from the file to a list. Next, for each of these lines, it writes an empty string, therefore clearing these lines.

Erase the last line

To remove the last line from the file, first, we have to count the number of lines in a file. Then we have to write an empty string to the last one.

Here’s the code:

file = open("D:/my_file.txt", "r")
lines = file.readlines()
last_line = len(lines) - 1
file.close()

file = open("D:/my_file.txt", "w")
for i, line in enumerate(lines):
    if i != last_line:
        file.write(line)
    else:
        file.write("")

file.close()

The following line returns the number of text lines in a file:

last_line = len(lines) - 1

We have to subtract one line because the indexing in the loop starts from 0 and not from 1.

The enumerate function returns the index of the current loop and a value. If the index is the same as the last_line – 1 then it writes “” instead of the current line.

Remove selected line

In a similar way, you can give a number of the line you want to remove. Let’s say you want to remove the second line from the file.

file = open("D:/my_file.txt", "r")
lines = file.readlines()
line_to_remove = 2
file.close()

file = open("D:/my_file.txt", "w")
for i, line in enumerate(lines):
    if i != line_to_remove - 1:
        file.write(line)
    else:
        file.write("")

file.close()

Remove selected lines

If you want to delete more than a single line, you can use a list of lines to remove. Let’s modify our file a bit by adding additional lines:

Run the code to remove multiple lines. In our case they will be 2, 5, and 7.

file = open("D:/my_file.txt", "r")
lines = file.readlines()
lines_remove = [2, 5, 7]
file.close()

file = open("D:/my_file.txt", "w")
for i, line in enumerate(lines):
    if i + 1 in lines_remove:
        file.write("")
    else:
        file.write(line)

file.close()

First, there are three numbers added to a list. These are the numbers of lines we want to remove.

lines_remove = [2, 5, 7]

Later in the code, we check if the current line is inside the list. If the condition is met, the line is removed from the file.

If you open the file, you will notice that selected lines are removed.

Clear lines with the provided string

You can remove lines that are the same as provided text.

file = open("D:/my_file.txt", "r")
lines = file.readlines()
file.close()

file = open("D:/my_file.txt", "w")
for line in lines:
    if line.strip("\n") != "Second line":
        file.write(line)

file.close()

The file content is saved as list elements.

In the next part, Python checks for each line whether the string equals the “Send line”. If it’s not then it writes it to a file, otherwise, it drops it.

The newline characters are stripped from the file for each line.

This is how our new file looks like:

You can also use substrings, insead of whole strings.

Just replace this line:

if line.strip("\n") != "Second line":

With this one:

if "Second" not in line.strip("\n"):

This code will remove all lines that contain the word “Second”. It’s case-sensitive.

The result is the same as in the previous example.