Editing certain line of a file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Editing certain line of a file

I have a text file which has 100 lines ; for example it's 75th line is "x" and I want change it to "y". What should I do?

20th Jun 2020, 9:14 PM
Mr.Lightning
Mr.Lightning - avatar
4 Answers
+ 3
I did get you, but I think you didn't get me. You can read in your whole file, and then every line will be just a string in a list. So your line 75 would be thatlist[74], it's just regular Python. I made a small demonstration: https://code.sololearn.com/c1t40xJ5RwJG/?ref=app
20th Jun 2020, 10:05 PM
HonFu
HonFu - avatar
+ 2
HonFu I think you didn't get what I meant; If I append something it adds to the end of my text file. If I write something it overwrites the whole file. I want to change something in the middle of the file.
20th Jun 2020, 9:52 PM
Mr.Lightning
Mr.Lightning - avatar
+ 2
Ok The problem is solved now.
20th Jun 2020, 10:06 PM
Mr.Lightning
Mr.Lightning - avatar
0
You can read your file in, for example with the file object method readlines. That will give you a regular list with regular strings in it which you can just manipulate like you normally do in a code. Are you familiar with the basic file handling stuff? You might wanna look for tutorials like this: https://www.pythonforbeginners.com/cheatsheet/JUMP_LINK__&&__python__&&__JUMP_LINK-file-handling/
20th Jun 2020, 9:48 PM
HonFu
HonFu - avatar