By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
with
File I/O (Input/Output) is how your Python scripts read from and write to files—CSVs, JSON, Parquet, logs, or even raw binary data. Context managers (the with statement) are Python’s way of ensuring files are properly opened, used, and closed—even if your code crashes mid-operation.
You’re building a daily ETL pipeline that: 1. Reads a 10GB CSV from S3.2. Cleans the data with pandas.3. Writes the result to a Parquet file.4. Uploads it back to S3.
If you don’t use a context manager, your script might: - Crash mid-write, leaving a corrupted Parquet file.- Leak file handles, causing the next run to fail with Too many open files.- Leave temporary files on disk, filling up your server’s storage.
Too many open files
Context managers fix all of this automatically.
OSError: [Errno 24] Too many open files
open()
'r'
'w'
'a'
encoding='utf-8'
UnicodeDecodeError
'r+'
'b'
file.close()
read()
readlines()
readline()
file.read()
file.readlines()
file.readline()
pandas.read_csv()
to_csv()
index=False
json.load()
json.dump()
load()
dump()
indent=2
pathlib.Path
os.path
Path('file.txt').read_text()
pathlib
data.csv
id
name
value
pip install pandas
Build a script that: 1. Reads a CSV file.2. Filters rows where value > 100.3. Writes the result to a new CSV.4. Handles errors gracefully (e.g., missing file, corrupt data).
value > 100
# ❌ DON'T DO THIS IN PRODUCTION file = open('data.csv', 'r') data = file.read() file.close() # What if an error happens before this line?
Problem: If file.read() fails, file.close() never runs → resource leak.
# ✅ Safe and clean with open('data.csv', 'r', encoding='utf-8') as file: data = file.read() # File is automatically closed here, even if an error occurs
import pandas as pd try: df = pd.read_csv('data.csv') print("Original data shape:", df.shape) except FileNotFoundError: print("❌ Error: File not found. Check the path.") exit(1) except pd.errors.EmptyDataError: print("❌ Error: File is empty.") exit(1) except Exception as e: print(f"❌ Unexpected error: {e}") exit(1)
Why this matters:- pd.read_csv() handles encoding, missing values, and data types automatically.- The try/except block prevents crashes in production.
pd.read_csv()
try/except
filtered_df = df[df['value'] > 100] # ✅ Safe write with context manager with open('filtered_data.csv', 'w', encoding='utf-8') as file: filtered_df.to_csv(file, index=False) # index=False avoids extra column
Key details:- index=False prevents pandas from adding an extra "Unnamed: 0" column.- encoding='utf-8' ensures special characters (e.g., é, ñ) are saved correctly.
é
ñ
# Process a 10GB file without loading it all into memory chunk_size = 10_000 # Rows per chunk with pd.read_csv('large_data.csv', chunksize=chunk_size) as reader: for i, chunk in enumerate(reader): filtered_chunk = chunk[chunk['value'] > 100] # Append to output file (mode='a' for append) with open('filtered_large_data.csv', 'a', encoding='utf-8') as f: filtered_chunk.to_csv(f, header=(i == 0), index=False)
Why this matters:- Memory efficiency: Only loads chunk_size rows at a time.- Header handling: header=(i == 0) ensures the header is only written once.
chunk_size
header=(i == 0)
from pathlib import Path input_path = Path('data.csv') output_path = Path('filtered_data.csv') if not input_path.exists(): print(f"❌ Error: {input_path} does not exist.") exit(1) df = pd.read_csv(input_path) filtered_df = df[df['value'] > 100] filtered_df.to_csv(output_path, index=False)
Advantages:- Cross-platform: Works on Windows, Linux, and macOS.- Readable: Path('file.txt').read_text() is cleaner than open('file.txt').read().
open('file.txt').read()
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename='pipeline.log' ) try: df = pd.read_csv('data.csv') logging.info(f"Read {len(df)} rows from data.csv") filtered_df = df[df['value'] > 100] filtered_df.to_csv('filtered_data.csv', index=False) logging.info(f"Wrote {len(filtered_df)} rows to filtered_data.csv") except Exception as e: logging.error(f"Pipeline failed: {e}", exc_info=True) raise # Re-raise to fail the job (e.g., in Airflow)
Why this matters:- Debugging: Logs help you trace failures in production.- Audit trail: You can track how many rows were processed.
python import os input_path = os.getenv('INPUT_PATH', 'data.csv') # Fallback to 'data.csv'
.php
.csv
python if not input_path.endswith('.csv'): raise ValueError("Only CSV files are allowed.")
tempfile
python import tempfile with tempfile.NamedTemporaryFile(delete=True) as tmp: df.to_csv(tmp.name) # Process tmp.name, then it's automatically deleted
gzip
python df.to_csv('data.csv.gz', index=False, compression='gzip')
python df.to_parquet('data.parquet', engine='pyarrow')
python if output_path.exists(): logging.warning(f"{output_path} already exists. Overwriting.")
python temp_path = output_path.with_suffix('.tmp') df.to_csv(temp_path, index=False) temp_path.rename(output_path) # Atomic operation
python logging.info(f"Input file size: {input_path.stat().st_size / 1e6:.2f} MB")
time.time()
python import time start = time.time() df = pd.read_csv(input_path) logging.info(f"Read took {time.time() - start:.2f} seconds")
encoding='latin1'
MemoryError
pd.read_csv(chunksize=...)
FileNotFoundError
Path('file').exists()
os.getenv()
readlines() → List of lines (memory-heavy for large files).
"Why should you use with instead of open() + close()?"
close()
with guarantees the file is closed, even if an error occurs.
"What happens if you open a file in 'w' mode and it already exists?"
The file is truncated (erased) immediately.
"How do you read a CSV file in chunks with pandas?"
pd.read_csv('file.csv', chunksize=1000).
pd.read_csv('file.csv', chunksize=1000)
"What’s the risk of not specifying encoding when opening a file?"
encoding
to_csv
"You’re processing a 50GB CSV file. Your script crashes with MemoryError. What’s the most efficient fix?"- ❌ Increase server RAM (expensive and not scalable).- ✅ Use pd.read_csv(chunksize=10_000) to process in chunks.
pd.read_csv(chunksize=10_000)
Write a script that: 1. Reads a JSON file (config.json) with this structure: json { "input_path": "data.csv", "output_path": "output.parquet", "threshold": 100 } 2. Reads the CSV file specified in input_path.3. Filters rows where the column value > threshold.4. Writes the result to output_path in Parquet format.5. Handles errors (missing file, invalid JSON, corrupt CSV).
config.json
json { "input_path": "data.csv", "output_path": "output.parquet", "threshold": 100 }
input_path
threshold
output_path
import json import pandas as pd from pathlib import Path # Read config try: with open('config.json', 'r', encoding='utf-8') as f: config = json.load(f) except FileNotFoundError: print("❌ config.json not found.") exit(1) except json.JSONDecodeError: print("❌ config.json is not valid JSON.") exit(1) # Validate paths input_path = Path(config['input_path']) output_path = Path(config['output_path']) if not input_path.exists(): print(f"❌ Input file {input_path} not found.") exit(1) # Read and filter data try: df = pd.read_csv(input_path) filtered_df = df[df['value'] > config['threshold']] filtered_df.to_parquet(output_path) print(f"✅ Success! Wrote {len(filtered_df)} rows to {output_path}.") except Exception as e: print(f"❌ Error: {e}") exit(1)
Why it works:- Uses with for safe file handling.- Validates inputs before processing.- Converts to Parquet (efficient for analytics).- Handles errors gracefully.
with open('file.txt', 'r', encoding='utf-8') as f:
with open('file.txt', 'w', encoding='utf-8') as f:
content = f.read()
for line in f:
df = pd.read_csv('file.csv')
df.to_csv('file.csv', index=False)
data = json.load(f)
json.dump(data, f, indent=2)
Path('file.txt').exists()
Path('file.txt').stat().st_size
None
utf-8
with open('file.txt') as f:
with open('in.txt') as fin, open('out.txt', 'w') as fout:
@contextmanager
try/finally
__exit__
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.