Search code examples
pythonlistmoduleiooverwrite

Modify list with io module in python


I'm trying to overwrite a line of text with the io module, the problem is that when I run my script and check my .txt the line that I overwritten is fine except for the end of the file.

from io import open

text = open("tst.txt", "r+")
list_j = text.readlines()
list_j[0] = "Modified\n"
text.seek(0)
text.writelines(list_j)
text.close

txt file before

first line of text
second line of text
third line of text
fourth line of text

txt file after

Modified
second line of text
third line of text
fourth line of text
 of text


Solution

  • The replacement code is okay. You gotta edit 9th line to write it to the file correctly.

    from io import open
    
    text = open("tst.txt", "r+")
    list_j = text.readlines()
    list_j[0] = "Modified\n"
    text.seek(0)
    #text.writelines(list_j)
    with open('tst.txt', 'w+') as the_file:
        for x in list_j:
            the_file.write(x)
    text.close