Text file processing :- How to delete a line in text file using Python
Let us start by creating a simple text file ‘myfile‘, Content of the file is as follows.
This is the first line Second line The third line I love Python I love PHP Text file processing
The python script we are going to create will delete a specific line starting with the word defined. The line to be deleted is assigned to the variable “str“.
#!/usr/bin/python def deleteLine(): fn = 'myfile' f = open(fn) output =  str="The" for line in f: if not line.startswith(str): output.append(line) f.close() f = open(fn, 'w') f.writelines(output) f.close() deleteLine()
In this script we are going to delete third line which starts with “The“, Hence we assign ‘str=”The”‘. You can change this value to any according to your requirement.
How function deleteLine() works?
1)Inside this function we are defining the file name “myfile”
2)Open the file
3)Assign an array named output.
4)Assign ‘str’ to line which needs to be deleted.
5)Then reading each line and appending all lines to output array which doesn’t start with line “The”
6)We are closing the file using f.close()
7)Next step is to open the file again and write data which is saved to “output” array to the same file.
8)Note that in this specific example we are opening the file reading each line and then saving in toÂ output array. Then open same file again and write data to it.
Last step is to call this function deleteLine().Â It is very simple and I am not going to confuse you with any other steps. Hope this script will be useful for some of you around .