Python Forum

Full Version: Write to file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Say you have a txt. document where you want to write specific information to line 1,2,3,4 and 5 every time. Is there a way to specify this in my code?

The reason I'm asking is because my code seems to write to a different line when i run the program several times.
A whole text file is merely a sequence of (unicode) characters. The computer doesn't see it as a two dimensional item as we do in a text editor. If the file is small with only a few lines as your post suggests, I would recommend reading the whole file as a list of strings and then write the whole file back on disk.
with open('spam.txt') as ifh:
    lines = list(ifh)
lines[1] = 'hello world\n'
lines[3] = 'change something\n'
with open('spam.txt', 'w') as ofh:
    ofh.writelines(lines)