Learn how to manage errors and perform file operations effectively in Python. This section covers exception handling, context managers, and file I/O, which are critical for building reliable applications.
6 audio · 1:36
Nortren·
How do you open and read a file?
0:16
Use the built-in open function with the path and mode. Wrap it in a with statement to ensure the file is closed automatically. Reading methods include read for everything, readline for one line, readlines for all lines as a list, and iterating directly over the file object for line-by-line reading.
What is the difference between text mode and binary mode?
0:15
Text mode, the default, returns strings and handles newline conversion and encoding. Binary mode, indicated by b in the mode string, returns bytes and reads raw bytes without any conversion. Use binary mode for non-text files like images or for precise byte-level control.
How does Python handle text encoding when reading files?
0:15
When opening a file in text mode, you should specify the encoding parameter, typically utf-8. Without it, Python uses the platform-dependent default, which can lead to portability bugs. Starting with Python 3.15 there is work toward making UTF-8 the default for all platforms.
The json module provides functions for serializing Python objects to JSON and deserializing JSON to Python. The main functions are dumps and loads for strings, dump and load for files. Only basic types map directly: dict, list, str, int, float, bool, and None.
JSON is a text-based, language-independent format that supports only basic types. It is readable and safe to load from untrusted sources. Pickle is a binary format that can serialize almost any Python object, including custom classes. Pickle is unsafe with untrusted data because loading can execute arbitrary code.
The csv module reads and writes comma-separated values files. It handles quoting, escaping, and different dialects. The DictReader and DictWriter classes allow row access by column name instead of index. For complex tabular data, libraries like pandas are usually a better choice.
---