Skip to content

Instantly share code, notes, and snippets.

@jnaulty
Created August 2, 2021 08:41
Show Gist options
  • Save jnaulty/2dfb912c86504f666651e0b109966831 to your computer and use it in GitHub Desktop.
Save jnaulty/2dfb912c86504f666651e0b109966831 to your computer and use it in GitHub Desktop.
#https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python
def insert_file(filename, index, value):
with open(filename, "r") as f:
contents = f.readlines()
contents.insert(index, value)
with open(filename, "w") as f:
contents = "".join(contents)
f.write(contents)
# echo "test\nworld" > test.txt
insert_file('test.txt', 1, '# hello\n')
# cat test.txt
# test
# # hello
# world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment