13.5. File Append
Appends data at the end of file
Creates file if not exists
Works with both relative and absolute path
Fails when directory with file cannot be accessed
mode
parameter toopen()
function is required.writelines()
does not add a line separator!!
13.5.1. Open File for Appending
Python will create file if it does not exist
By default, file is opened in text mode
Always remember to close file
>>> file = open('/tmp/myfile.txt', mode='a') # write in text mode
>>> file = open('/tmp/myfile.txt', mode='at') # write in text mode
>>> file = open('/tmp/myfile.txt', mode='ab') # write in binary mode
13.5.2. Append to File
Append line at the end of a file
Remember to add a newline character at the end of the line
Remember to close the file
>>> line = 'This is a line\n'
>>>
>>> file = open('/tmp/myfile.txt', mode='a')
>>> file.write(line)
15
>>> file.close()
13.5.3. Context Manager
Context managers use
with ... as ...:
syntaxContext manager closes the file automatically upon block exit (dedent)
Remember to add a newline character at the end of the line
>>> line = 'This is a line\n'
>>>
>>> with open('/tmp/myfile.txt', mode='a') as file:
... file.write(line)
15