File Handling in Python
File Handling in Python
Introduction
File handling is a mechanism that allows Python programs to read data from disk files and write data back to disk files. Unlike standard input/output which is temporary, file handling enables permanent data storage.
Data Files
Data files can be stored in two formats:
• Text Files: Store information in ASCII/Unicode characters. Each line ends with an EOL (End of Line) character (\n, \r, or both).
• Binary Files: Store data in the same format as in memory, making them faster and more efficient but not directly readable.
Steps in File Handling
1. Opening a File: Using open(filename, mode).
2. Performing Read/Write Operations: Using functions like read(), write(), etc.
3. Closing the File: Using close() to release resources.
Opening Files
Syntax: file_object = open(filename, mode)
Modes:
• ‘r’: Read (default).
• ‘w’: Write (overwrites existing file).
• ‘a’: Append (adds to existing file).
• ‘b’: Binary mode (e.g., ‘rb’, ‘wb’).
• ‘+’: Read and write (e.g., ‘r+’, ‘w+’).
Example:
myfile = open(“story.txt”, “r”) # Opens for reading
Closing Files
Use file_object.close() to release the file.
Example:
myfile = open(“data.txt”, “r”)
content = myfile.read()
myfile.close()
Reading from Files
Methods:
• read(size): Reads size bytes (or entire file if size is omitted).
• readline(size): Reads a line (up to size bytes).
• readlines(): Reads all lines into a list.
Example:
myfile = open(“data.txt”, “r”)
line1 = myfile.readline() # Reads first line
lines = myfile.readlines() # Reads all remaining lines
myfile.close()
Writing to Files
Methods:
• write(string): Writes a string to the file.
• writelines(list): Writes a list of strings to the file.
Example:
myfile = open(“output.txt”, “w”)
myfile.write(“Hello, World!\n”)
myfile.writelines([“Line 1\n”, “Line 2\n”])
myfile.close()
File Pointer
Tracks the current position for read/write operations.
Use seek(offset, whence) to move the pointer:
• whence=0: Start of file (default).
• whence=1: Current position.
• whence=2: End of file.
Example:
myfile = open(“data.txt”, “r”)
myfile.seek(10) # Moves pointer to 10th byte
Binary File Operations
Using pickle Module:
Pickling (Writing):
import pickle
data = [1, 2, 3]
with open(“data.bin”, “wb”) as f:
pickle.dump(data, f)
Unpickling (Reading):
import pickle
with open(“data.bin”, “rb”) as f:
loaded_data = pickle.load(f)
CSV File Handling
Reading CSV:
import csv
with open(“data.csv”, “r”) as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
Writing CSV:
import csv
with open(“data.csv”, “w”) as csvfile:
writer = csv.writer(csvfile)
writer.writerow([“Name”, “Age”])
writer.writerow([“Alice”, 25])
Absolute vs. Relative Paths
• Absolute Path: Full path from the root (e.g., C:\folder\file.txt).
• Relative Path: Path relative to the current directory (e.g., .\subfolder\file.txt).
Example:
import os
current_dir = os.getcwd() # Gets current working directory
Standard Streams
• sys.stdin: Standard input (keyboard).
• sys.stdout: Standard output (monitor).
• sys.stderr: Standard error (monitor).
Example:
import sys
sys.stdout.write(“Hello, World!\n”)
Key Points
• Always close files after use or use with statements for automatic closure.
• Binary files are more efficient for structured data.
• Use pickle for serializing Python objects.
• CSV files are ideal for tabular data.