Highlights from this chapter include:
- Python can read and write data in files using the built-in
open()
function. - Due to buffering, changes to a file may not be visible until the file is closed.
- Newline characters need to be removed/added when reading/writing files.
- Comma-separate-value (CSV) files are commonly used to represent data.
- Exceptions that cause a program to terminate can be handled using
try
andexcept
. - Raising an exception is an alternative way to return from a function when an error occurs.
Statement | Description |
---|---|
|
Open a file for reading. |
|
Open a file for writing. |
|
Open a file for appending. |
|
Close a file after making changes. |
|
Read the entire contents of a file. The variable |
|
Read the next line of a file. The variable |
|
Read all lines of a file. The variable |
|
Writes a line to a file. In contrast to |
|
Writes multiple lines to a file. As with |
try:
# Statements
except:
# Statements
|
Try to run statements that might raise an error. If any error is raised, run other statements. |
try:
# Statements
except ValueError:
# Statements
|
Try to run statements that might raise a |
try:
# Statements
except ValueError as err:
# Statements
|
Try to run statements that might raise a |
raise ValueError
|
Raises a |
raise ValueError("number is prime")
|
Raises a |