Python: Files, Exceptions, and Errors


Opening files using the with statement is recommended because it ensures that the file is automatically closed at the ends of the with the statement.

# Open file -> close it, or use "with as":
# r - read, w - write, a - append, r+ - read and write
>>> with open('filename.txt', 'r') as file_object:
...     content =
...     print(type(content))
...     print(content)
...     print(content.rstrip())
<class 'str'>
line 1 in the file
line 2 in the file
line 3 in the file

line 1 in the file
line 2 in the file
line 3 in the file

#The blank line in the second print appears 
#because read() returns an empty string when it reaches the end of the file => rstrip()

# line into the list:

>>> with open('filename.txt', 'r') as file_object:
...     lines = file_object.readlines()
>>> print(lines)
['line 1 in the file\n', 'line 2 in the file\n', 'line 3 in the file\n']
>>> for line in lines:
...     print(line.rstrip())
line 1 in the file
line 2 in the file
line 3 in the file

#to scan a text file line by line, file iterators are often your best option:
>>> for line in open('myfile'): # Use file iterators, not reads
... print(line, end='')
hello text file
goodbye text file


Standard exceptions and users exceptions

It’s better to catch and work with the specific exception

try/except could include:

  • else, that will be executed if no exception occurred
  • finally, will be executed no matter what (good to closed sockets or files)

Access to Exception

1. Using as: Each error has some attributes that could be used like OSError has errno and strerror, that could be used for debugging etc.

2. Using args: custom message and can do anything you would like


Assert of True – nothing
Assert of False – AssertionsError exception

Just for developers during writing the code. No need to use it for the user input check.