Table of Contents

Reading a file

Line by line

>>> for line in open("./dico.txt", "r"):
...   print(line)
... 
ABACA~
 
ABACULE~
 
ABAISSABLE~
 
ABAISSAIENT~
 
ABAISSAIS~
.
.
.

Classic method

>>> a_file = None
>>> try:              
...   a_file = open("./dico.txt", "r")
...   text = a_file.read()
... except:
...   print("Error")
... finally:
...   if a_file != None:
...     a_file.close()
... 
>>> 
>>> a_file
<_io.TextIOWrapper name='./dico.txt' encoding='UTF-8'>
>>> a_file.name
'./dico.txt'

The with statement

The better solution. No need to use try: … except: ….
Forget the previous method.

>>> with open("./dico.txt", "r") as f:
...   text = f.read()
>>>
>>> len(text)
2664170
>>> print(text)
.
.
.
ZYGOMORPHE~
ZYGOMYCETES~
ZYGOMYCETE~
ZYGOPETALE~
ZYGOTE~
ZYMASE~
ZYMOTECHNIE~
ZYMOTIQUE~
ZYTHON~
ZYTHUM~
Z~

This code calls open(), but it never calls a_file.close(). The with statement starts a code block, like an if statement or a for loop. Inside this code block, you can use the variable a_file as the stream object returned from the call to open(). All the regular stream object methods are available — seek(), read(), whatever you need. When the with block ends, Python calls a_file.close() automatically.