file = open("filename.txt", "mode")
"r": Read (default). Opens for reading. Raises error if file doesn't exist.
"w": Write. Creates a new file or overwrites existing content.
"a": Append. Adds content to the end of an existing file.
"x": Exclusive creation. Fails if the file exists.
"b": Binary mode (e.g., "rb" or "wb") for non-text files: images, videos, etc.
"t": Text mode (default).
"+": Read/write mode (e.g., "r+" or "w+").
file = open("example.txt")
# ... operations
file.close()
The with block automatically closes the file, even if an error occurs:
with open("example.txt") as file:
data = file.read()
# File is automatically closed here
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt") as file:
for line in file: # Reads one line at a time, memory efficient
print(line.strip()) # strip() removes newline characters
lines = file.readlines() # Returns a list of lines
print(lines[0]) # Print first line
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
with open("example.txt", "a") as file:
file.write("\nThis is appended text.")
with open("source.txt", "r") as src, open("dest.txt", "w") as dest:
dest.write(src.read())
Use try-except blocks to handle file errors:
try:
with open("missing_file.txt") as file:
data = file.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")
read(size) — Reads size bytes (or entire file).
readline() — Reads one line.
readlines() — Returns a list of all lines.
write(text) — Writes a string to the file.
writelines() — Writes a list of strings.
seek(offset) — Moves cursor to offset.
tell() — Returns current cursor position.
import os
import shutil
# File operations
os.rename("old.txt", "new.txt")
os.remove("file.txt")
os.path.exists("file.txt")
# Directory operations
os.mkdir("new_dir")
shutil.copy2("src.txt", "dest.txt")
pathlib — represents paths as objects rather than strings
Works consistently across Windows / Linux / macOS
from pathlib import Path
path = Path("folder/file.txt")
print(path.parent) # folder
print(path.suffix) # .txt
# Check existence
print(path.exists()) # True
# Reading with pathlib
content = path.read_text()
# Writing with pathlib
path.write_text("Hello world!")
Use Python’s built-in csv module to work with CSV (Comma-Separated Values) files
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
import csv
data = [
["Name", "Age"],
["Alice", 22],
["Bob", 25]
]
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
Use Python’s json module.
import json
data = {"name": "Alice", "age": 22}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
Working with tabular data (rows & columns)
Data cleaning
Data analysis
Data transformation
Reading/Writing files like CSV, Excel, JSON, SQL, etc.
Series — 1D labeled data (one column)
DataFrame — 2D labeled data (rows & columns)
import pandas as pd
# Read
# df = DataFrame
df = pd.read_csv("data.csv")
print(df)
# Write
# index=False → NOT to write row numbers
df.to_csv("output.csv", index=False)
df.head() — View first few rows
df.tail() — View last few rows
df.columns — Get column names
df["Age"] — Select a column
df[df["Age"] > 20] — Filter rows
df["NewCol"] = df["Age"] + 5 — Add a new column
df = df.drop("NewCol", axis=1) — Drop a column