File Handling & Error Handling
Real data work means reading files, writing outputs, and handling errors gracefully. A script that crashes on bad data is not production-ready.
How do you read and write a text file in Python?
# Read:
with open("data.txt", "r") as f:
content = f.read()
# Write:
with open("output.txt", "w") as f:
f.write("Hello, World!")
# Append:
with open("log.txt", "a") as f:
f.write("New log entry\n")Always use the with statement — it automatically closes the file even if an error occurs. "r" = read, "w" = write (overwrites), "a" = append.
How do you read a CSV file in Python without Pandas?
import csv
with open("data.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["salary"])DictReader gives each row as a dictionary keyed by column name. In practice you will use Pandas for CSV files, but knowing the csv module shows depth of knowledge.
How do you handle errors with try-except?
try:
x = int("not_a_number")
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("This always runs")try-except prevents a script from crashing on bad data. finally runs cleanup code (close connections, log completion). In data pipelines, wrap file reads and API calls in try-except.
How do you read a JSON file in Python?
import json
# Read:
with open("data.json", "r") as f:
data = json.load(f)
# Write:
with open("output.json", "w") as f:
json.dump(data, f, indent=2)
# String to dict:
d = json.loads('{"name": "Rahul", "age": 28}')JSON is the standard format for API responses. json.load() reads from a file; json.loads() parses a string. In analytics, you frequently convert JSON API responses into Pandas DataFrames.
How do you use os and os.path to work with file paths?
import os
os.getcwd() # current directory
os.listdir(".") # list files
os.path.exists("data.csv") # True/False
os.path.join("data", "sales.csv") # "data/sales.csv"
os.makedirs("output", exist_ok=True) # create folderos.path.join() is critical for cross-platform scripts — never hardcode "/" or "\" separators. exist_ok=True in makedirs prevents errors if the folder already exists.
EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS
Want to master Python with live practice?
Join our Python for Data Analysis course — live classes in Noida and online across India.
Book Free Demo Class →