Python Read and Write Files

Hello Stefanio

Yes it is possible to delete a particular line within a file. Specifically, you must call file.readlines() to get a list of all the lines in that file. You can then use list indexing to edit a specific line. You can do it like so:

Let’s say you have a text file called my_text.txt that contains the following lines:

Line1
Change This Line
Line3

Use the following code:

a_file = open("my_text.txt", "r")
list_of_lines = a_file.readlines()
list_of_lines[1] = "Line2\n"

a_file = open("my_text.txt", "w")
a_file.writelines(list_of_lines)
a_file.close()

The resulting contents of my_text.txt is:

Line1
Line2
Line3

I hope this has been helpful!

Laz

1 Like