Skip to content Skip to sidebar Skip to footer

How To Edit A Line In A Notepad File Using Python

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a speci

Solution 1:

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 informationwithopen(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\n'# write updated information      withopen(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+):

withopen(src, 'r+') as fobj:
    data = fobj.readlines()
    data[ix] = 'some new info\n'
    fobj.seek(0) # reset file pointer...
    fobj.writelines(data)

Solution 2:

You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.

f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()

Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')

f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
    if i == Which_Line:
        f.writelines(str(Edit)+"\n")
    else:
        f.writelines(line)
f.close()

Post a Comment for "How To Edit A Line In A Notepad File Using Python"