How to delete a line from a file in Python

Deleting a line from a file returns a file with all the lines except the removed line. This can be done with or without knowing the index of the line. For example, deleting a line line2 from a file containing line1\nline2\nline3\n will return line1\nline3\n.

Solution for How to delete a line from a file in Python : You can use a for loop to delete a line from a file where its position is unknown Open a file to read with open(“file”, “r”). Use file.readlines() to create a list where each element is a line from the file. Close the file. Open the file again to write with open(“file”, “w”). Use a for-loop to iterate through the list of lines, and use the syntax line in lines to look for the line that is going to be deleted. Use file.write() to write all lines except the deleted line to the file.

Solution for How to delete a line from a file in Python : You can use a for loop to delete a line from a file where its position is unknown Open the file for reading and use file.readlines() to create a list where each element is a line from the file. Use the syntax del list[index] with list as the list of lines to delete the element at index. Write the edited list of lines to a file to create a new file without the deleted line.

sample.txt


how-to-delete-a-line-from-a-file-in-python