Pawel Bala
Pawel Bala

Reputation: 93

Comment/uncomment particular txt line in python

I'd like to take a text file, and for each line, try to comment that line (write to file), check whether an external script works, and if not, uncomment it. Finally, this should result in a txt file with unnecessary code lines commented out.

I tried to copy the text file into a list, and then iterate over it, each time writing the entire file. Is there a better solution?

Upvotes: 0

Views: 249

Answers (1)

Dolda2000
Dolda2000

Reputation: 25855

I tried to copy the text file into a list, and then iterate over it, each time writing the entire file. Is there a better solution?

No, there isn't really any vastly better solution. You need move around all the data following the line anyway, since you're adding or removing text in the middle of the file.

In the best case, you could optimize your program to only move the data after the line you're currently editing, but that optimization is going to be rather minor anyway, and still not effect the actual scaling of the program as a whole, so I'd argue it isn't worth it.

Certainly, the actual running of the program is going to be vastly more expensive than just writing the file anyway, so optimizing that part doesn't matter much. :)

Upvotes: 1

Related Questions