you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src
to a variable data
line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst
.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info
'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open
with r+
):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info
'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…