AW: how to replace line on particular line in file[no need to write it back whole file again]
Lutz Horn
lutz.horn at outlook.de
Thu Oct 11 07:05:48 EDT 2018
Try something like this:
```
import sys
def replace(lineno, replacement):
for i, line in enumerate(sys.stdin.readlines()):
if i == lineno:
line = replacement
print(line.strip())
replace(2, "REPLACEMENT")
```
________________________________________
Von: Python-list <python-list-bounces+lutz.horn=outlook.de at python.org> im Auftrag von Iranna Mathapati <iranna.gani28 at gmail.com>
Gesendet: Donnerstag, 11. Oktober 2018 11:44
An: python list
Betreff: how to replace line on particular line in file[no need to write it back whole file again]
Hi Team,
How to replace particular line text with new text on a file
i have below code but its writing whole code.
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
out = open(file_name, 'w')
out.writelines(lines) <<<<< *writing back whole file instead of
particular line*
out.close()
replace_line('stats.txt', 0, 'good')
Thanks,
Iranna M
--
https://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list