How to delete specific lines of a text file using python ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to delete specific lines of a text file using python ?

python geeks

25th Mar 2018, 2:35 PM
Hesham Adel
Hesham Adel - avatar
2 Answers
+ 6
f = open("file", "r+") delete = 2 count = 0 for line in f: count++ if(count != delete): f.write(line); f.write("\n"); Untested but should work. At least you get the idea.
25th Mar 2018, 2:46 PM
Toni Isotalo
Toni Isotalo - avatar
+ 3
i guess read the file, save all lines as String elements of an array. modify the array as you wish (add/remove/edit lines/ elements). and overwrite your file with a new one containing every line of your array.
25th Mar 2018, 2:41 PM
seamiki
seamiki - avatar