User Tools

Site Tools


cs_lang:python:things-to-know:files

This is an old revision of the document!


Reading a file

Line by line

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

Classic method

>>> try:              
...   a_file = open("./dico.txt", "r")
... except:
...   print("Error")
... finally:
...   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: ….

>>> with open("./dico.txt", "r") as f:
...   a = f.read()
>>>
>>> len(a)
2664170
>>> print(a)
.
.
.
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.

cs_lang/python/things-to-know/files.1292177795.txt.gz · Last modified: 2010/12/12 19:16 by cedric