What is a File?
Variables and lists store data in RAM. This data is temporary — it disappears when the program stops. Files store data permanently on your hard disk.
We use the built-in open() function to work with files in Python.
Text Files vs Binary Files
| Feature | Text Files | Binary Files |
|---|---|---|
| Content | Human-readable characters (letters, numbers, symbols) | Raw bytes (machine-readable data) |
| Examples | .txt, .csv, .py, .json | .jpg, .png, .pdf, .mp3 |
| Open mode | "r", "w", "a" | "rb", "wb", "ab" |
For this module, we will focus on text files since they are the most common in Python programming and data science.
File Opening Modes
When you open a file, you must tell Python what you plan to do with it:
| Mode | Name | What It Does |
|---|---|---|
"r" | Read | Opens for reading. Throws error if file does not exist. |
"w" | Write | Opens for writing. Creates new file or overwrites existing content. |
"a" | Append | Opens for adding data at the end. Does not delete existing data. |
"r+" | Read + Write | Opens for both reading and writing. File must exist. |
The open() Function
# Basic syntax
file = open("filename.txt", "mode")
# Example: Open a file for reading
file = open("notes.txt", "r")
When you open a file with open(), you must always close it when done using file.close(). If you forget, the file stays locked and other programs cannot access it. We will learn a better approach using the with statement in the next lesson.
Quick Summary
- File Operations: Built-in
open(filename, mode)function handles file I/O operations. - Access Modes:
'r'(read only, file must exist),'w'(write, overwrites existing file),'a'(append to end),'r+'/'w+'(read/write),'b'suffix (binary mode for media). - Resource Release: Files opened with raw
open()must be explicitly closed with.close()to release the operating system lock.
What's Next?
Let's look at how to safely read text from files using read(), readline(), and with open(...) in Reading Files!