0

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 specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?

#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()

#(This was my second attempt)    
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
Olivia
  • 11
  • 3
  • 3
    Possible duplicate of [Editing specific line in text file in Python](https://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python) – glibdud Oct 14 '19 at 13:53

2 Answers2

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 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\n'

# 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\n'
    fobj.seek(0) # reset file pointer...
    fobj.writelines(data)
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

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()