python change line in text file code example

Example 1: how to edit a specific line in text file in python

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

Example 2: python write text file on the next line

file = open("sample.txt", "w")
file.write("Hello\n")
file.write("World\n")
file.close()