Files

Read entire file into one big string

fh = open('file_path', 'r')
content = fh.read()
fh.close()

Read file line by line using iterator

fh = open('file_path', 'r')
for line in fh:
    print(line)
fh.close()

Read file line by line using while

fh = open('file_path', 'r')
line = fh.readline()
while line:
    print(line)
    line = fh.readline()
fh.close()

Write text to a file

fh = open('file_path', 'w')
fh.write('Hello World')
fh.close()

Write multiple lines of text to a file

fh = open('file_path', 'w')
# note the use of end-of-line \n
lines = ['first line\n', 'second line\n', 'third line']
fh.writelines(lines)
fh.close()

Append text to an existing file

# note the use of mode `a` - append
fh = open('file_path', 'a')
fh.write('text added at the end of file')
fh.close()