File Input/Output (I/O)
Programs often need to read data from files or write results back to files. Python makes file handling straightforward using the built-in open() function.
The open() Function
open(filename, mode) returns a file object.
| Mode | Meaning |
|---|---|
'r' | Read (default). File pointer is at the beginning. |
'w' | Write. Creates a new file or truncates (empties) existing content. |
'a' | Append. Adds data to the end of the file. |
Reading a File ('r' mode)
It is crucial to close the file after you are finished to release system resources.
Method 1: .read() (Reads entire file into a single string)
python file = open('data/sample.txt', 'r') content = file.read() print(content) file.close()
Method 2: .readline() (Reads one line at a time)
python file = open('data/sample.txt', 'r') line1 = file.readline() line2 = file.readline() file.close()
Method 3: Iterating over the file object (Most memory efficient)
This is the most Pythonic way to read large files line by line.
python file = open('data/sample.txt', 'r') for line in file: # line includes the newline character (\n), use line.strip() to remove it print(f"[LINE]: {line.strip()}") file.close()