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:
        # code to process download here
    except Exception as e:     # most generic exception you can catch
        logf.write("Failed to download {0}: {1}\n".format(str(download), str(e)))
        # optional: delete local version of failed download
    finally:
        # optional clean up code
        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)