{"id":9730,"date":"2021-06-18T16:49:50","date_gmt":"2021-06-18T11:19:50","guid":{"rendered":"https:\/\/pynative.com\/?p=9730"},"modified":"2021-07-03T12:04:53","modified_gmt":"2021-07-03T06:34:53","slug":"python-delete-lines-from-file","status":"publish","type":"post","link":"https:\/\/pynative.com\/python-delete-lines-from-file\/","title":{"rendered":"Delete Lines From a File in Python"},"content":{"rendered":"\n
This article lets you know how to delete specific lines from a file in Python. For example, you want to delete lines #5 and #12. <\/p>\n\n\n\n
After reading this article, you’ll learn<\/strong>:<\/p>\n\n\n\n Please follow the below steps to delete specific lines from a text file by line number: –<\/p>\n\n\n\n Example<\/strong>:<\/p>\n\n\n\n The following code shows how to delete lines from a text file by line number <\/strong>in Python. See the attached file used in the example and an image to show the file\u2019s content for reference.<\/p>\n\n\n\nTable of contents<\/h2>
Delete Lines from a File by Line Numbers<\/h2>\n\n\n\n
readlines()<\/code> method. here each element of a list is a line from the file<\/li>
enumerate()<\/code> function adds a counter to an iterable (such as list, string) and returns it in enumerate object. We used the enumerate object with a for loop to access the line number<\/li>