Home > Tips & Tricks > Delete a Line in Text File Using Python

Delete a Line in Text File Using Python

Let’s see how you can delete a line in a text file using python code. It is very simple just loop through each line and excludes the matched line with your specific variable and delete it.

Suppose you have a file like below and the name is myTextFile.txt.

Let’s now make a python code script to delete a specific line in the text file (myTextFile.txt).

In the above code, we made a function deleteSpecificLine() and open that text file to loop through each line. Then we compared with matching str each line and if matched then it will exclude that line and generate a new array to write again in that file.

Reference function:
startswith(): Returns true if the string starts with the specified value

There are many string functions. You can use it as per your requirments. Check all python string functions.

Hope you like it. If you have any query let me know. I would like to help you with that.

Being Tricky 😉

Photo of author

About Aman Mehra

Hey there! I'm Aman Mehra, a full-stack developer with over six years of hands-on experience in the industry. I've dedicated myself to mastering the ins and outs of PHP, WordPress, ReactJS, NodeJS, and AWS, so you can trust me to handle your web development needs with expertise and finesse. In 2021, I decided to share my knowledge and insights with the world by starting this blog. It's been an incredible journey so far, and I've had the opportunity to learn and grow alongside my readers. Whether you're a seasoned developer or just dipping your toes into the world of web development, I'm here to provide valuable content and solutions to help you succeed. So, stick around, explore the blog, and feel free to reach out if you have any questions or suggestions. Together, let's navigate the exciting world of web development!

Leave a Comment