Module 13 · File Handling — topic 2 of 15
Opening files
The open() function in detail: file name, mode and encoding arguments, the file object's attributes, what happens when a file is missing, and why the encoding you choose matters.
Learning objectives
- Call open() with the right arguments
- Inspect a file object's attributes
- Understand how encoding affects the bytes on disk
Definition
open(file, mode='r', encoding=None, ...) opens a file and returns a file object. The mode says whether you read, write or append, in text or binary; the encoding says how text is converted to bytes.
Introduction
Everything with files starts with open(). Getting its arguments right — especially mode and encoding — prevents most file bugs.
Why it matters
Opening a file in the wrong mode can erase it; opening with the wrong encoding garbles text. A few seconds of care avoids both.
Detailed explanation
The first argument is the path: a file name like "notes.txt" (relative to the current directory) or a full path.
The mode defaults to "r" (read text). Common modes: "w" write (creates or truncates), "a" append, "x" create only, plus "b" for binary. See the File modes lesson.
encoding applies only to text mode. UTF-8 handles every language and emoji; reading a file with a different encoding than it was written with produces garbled text or a UnicodeDecodeError.
The file object has attributes such as name, mode, encoding and closed, and methods such as read, write and close.
Opening a missing file for reading raises FileNotFoundError; opening a file without permission raises PermissionError.
Other useful arguments: newline (controls line-ending translation; CSV files use newline="") and errors (what to do with undecodable bytes, such as "replace").
Every successful open should be paired with a close; with statements do this for you.
Syntax
- open(path, mode, encoding).
- Default mode is "r".
- Pair every open with a close.
Code examples
File object attributes
notes.txt w utf-8 False True
Opening a missing file
cannot open: missing.txt
More examples
Encodings change the bytes
9 12 café ₹500 café ₹500
Step-by-step explanation
- The text has 9 characters, but UTF-8 needs 2 bytes for é and 3 for ₹, giving 12 bytes.
- Reading with the same encoding restores the original text.
- Reading the same bytes as cp1252 (a Windows encoding) produces 'mojibake' — the classic sign of an encoding mismatch.
Expected output
Running “Encodings change the bytes” prints exactly:
Practical applications
- Importing CSV exports from spreadsheet programs that use other encodings.
- Opening user-uploaded files safely.
Best practices
- Choose the mode deliberately.
- Specify the encoding for text files.
- Handle FileNotFoundError where a file may be missing.
Common mistakes
Opening with "w" to read
Avoid
Prefer
"w" truncates the file immediately — the data is already gone.
Important notes
- open() accepts pathlib.Path objects as well as strings.
Key takeaways
- open(path, mode, encoding) returns a file object.
- Wrong encoding means garbled text or errors.
- Missing files raise FileNotFoundError.
Try it yourself
- 1Write a Hindi or Tamil sentence to a file and compare its character and byte counts.
- 2Write a function that opens a file if it exists and otherwise returns a helpful message.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?
- ModerateWhich mode creates a new file but fails if the file already exists?