Skip to content

9618 · 20.2

File Processing and Exception Handling — FAQ

Frequently asked questions for 9618 File Processing and Exception Handling. Direct answers first, then deeper explanation — then practise with marking.

Why use `with open(...)` instead of `file = open(...)` and `file.close()`?

The with statement creates a context manager that guarantees the file will be closed automatically, even if your code raises an exception. If you manually open and close, you might forget to call close(), or an error might occur before close() is reached, leaving the file open and potentially leading to resource leaks or data corruption.

Should I just use a single `except:` to catch all errors?

No, this is generally bad practice. A bare except: (or except Exception:) catches everything, including system-exiting errors and keyboard interrupts. This can hide bugs and make your program difficult to debug. It's much better to catch specific exceptions that you know how to handle, like FileNotFoundError or ValueError.

What's the difference between `read()`, `readline()`, and `readlines()`?

read() reads the entire file content into a single string. readline() reads just one line from the file, including the newline character. readlines() reads all lines from the file and returns them as a list of strings.

How do I handle a file that uses a different character encoding?

The open() function has an encoding parameter. For example, if you know a file is encoded in UTF-8 (a very common standard), you would use open(myfile.txt,r,encoding=utf8)open('myfile.txt', 'r', encoding='utf-8'). Not specifying the encoding can lead to a UnicodeDecodeError if the file contains characters not supported by your system's default encoding.