File Functions
M3-R5.1 · Chapter 7: File Processing · 6 min read
File Functions — open() and close()
2.1 The open() Function
open() is the built-in Python function used to open a file. It returns a file object (also called a file handle) through which you perform read/write operations.
▸ Syntax
file_object = open(filename, mode, encoding=None)
# Parameters:
# filename : string — name/path of the file
# mode : string — how to open the file (default: 'r')
# encoding : string — character encoding (e.g., 'utf-8') for text files
▸ Examples
# Open for reading (default)
f = open('data.txt') # same as open('data.txt', 'r')
# Open for writing (creates file if not exists)
f = open('output.txt', 'w')
# Open for appending with encoding
f = open('log.txt', 'a', encoding='utf-8')
# Open binary file for reading
f = open('image.jpg', 'rb')
2.2 The close() Function
close() closes the file object and releases all system resources. After closing, the file can no longer be read or written through that object.
▸ Syntax
file_object.close()
▸ Example
f = open('data.txt', 'r')
# ... perform operations ...
f.close() # Always close the file after use!
# Check if file is closed
print(f.closed) # True if closed, False if open
📌 Important — Why Close Files?
Not closing files can lead to: (1) Data loss — buffered data may not be written to disk. (2) Resource leak — OS has a limit on open file handles. (3) File corruption — especially for binary/write modes.
2.3 The with Statement
Python's 'with' statement (context manager) automatically closes the file even if an exception occurs. This is the preferred way to handle files.
# Using 'with' — file closes automatically
with open('data.txt', 'r') as f:
content = f.read()
print(content)
# File is automatically closed here, even if error occurs
# Open multiple files at once
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
data = fin.read()
fout.write(data.upper())
3. Reading from a File
Python provides three main functions to read data from a text file:
3.1 read() Function
read(size) reads and returns the entire file content as a single string. If 'size' is given, reads only that many characters.
# Read entire file at once
f = open('sample.txt', 'r')
content = f.read() # Returns entire file as one string
print(content)
f.close()
# Read only first 50 characters
f = open('sample.txt', 'r')
chunk = f.read(50) # Read 50 characters
print(chunk)
f.close()
📌 Note
If the file is empty, read() returns an empty string ''. After reaching end of file, subsequent read() calls return ''.
3.2 readline() Function
readline(size) reads one complete line from the file (including the newline character '\n'). Returns an empty string '' when end of file is reached.
f = open('sample.txt', 'r')
line1 = f.readline() # Read first line
print(line1) # Output: 'Hello World\n'
line2 = f.readline() # Read second line
print(line2) # Output: 'Python is great\n'
# Loop to read all lines one by one
f.seek(0) # Go back to beginning
while True:
line = f.readline()
if line == '': # End of file
break
print(line, end='')
f.close()
3.3 readlines() Function
readlines() reads the entire file and returns a list of strings, where each element is one line (including '\n').
f = open('sample.txt', 'r')
lines = f.readlines() # Returns a list of all lines
print(lines)
# Output: ['Hello World\n', 'Python is great\n', 'File handling!']
# Access individual lines
print(lines[0]) # First line
print(len(lines)) # Total number of lines
# Loop through the list
for line in lines:
print(line.strip()) # strip() removes leading/trailing whitespace
f.close()
▸ Comparison: read() vs readline() vs readlines()
|
Function |
Returns |
Use Case |
Memory Usage |
|
read() |
Single string (entire file) |
Small files, need all content at once |
High (whole file in RAM) |
|
readline() |
One line as a string |
Process line by line, large files |
Low (one line at a time) |
|
readlines() |
List of strings (all lines) |
Need all lines as a list for indexing |
High (all lines in RAM) |
▸ Best Practice: Using for Loop to Read
# Most Pythonic way to read a file line by line
with open('sample.txt', 'r') as f:
for line in f: # File object is iterable!
print(line.strip())
# This is memory-efficient — reads one line at a time