python append to specific line python code example
Example 1: append a line to a text file python
# Open a file with access mode 'a'
file_object = open('sample.txt', 'a')
# Append 'hello' at the end of file
file_object.write('hello')
# Close the file
file_object.close()
Example 2: python insert on a specific line from file
f = open("path_to_file", "r")
contents = f.readlines()
f.close()
contents.insert(index, value)
f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()