This entry provides code to read text files in python.  The open function returns a handle that can be treated as a sequence of strings.  The file handle also has a read method that returns the file content in a string.

Reading Files

A file handle open for read can be treated as a sequence of strings.

try:
   file = open('some-file.txt')
except:
   print('File cannot be opened')
   quit()
for line in file:
   print(line)

The read method returns the entire file content in a single string:

file = open('some-file.txt')
all = file.read()