python write at the end of a file code example
Example 1: python append to file
with open(filename, "a+") as f:
f.write('Hello World')
Example 2: python write error to file
logf = open("download.log", "w")
for download in download_list:
try:
except Exception as e:
logf.write("Failed to download {0}: {1}\n".format(str(download), str(e)))
finally:
pass
Example 3: python write into file at position
mystring = 'some string'
pos = 10
with open('/path/to/file.txt', 'r+') as f:
contents = f.read()
contents = contents[:pos] + mystring + contents[pos + 1:]
f.seek(0)
f.truncate()
f.write(contents)