Almost every useful Python script touches files at some point. You read a configuration file before a program starts, write a log as it runs, load a CSV export from another tool, or save results as JSON for a web API to consume. The python read write file operations are deliberately simple: a built-in open() function, a small set of modes, and the with statement to guarantee files are closed properly. On top of that foundation, the standard library provides a csv module for tabular data and a json module for structured data, so most everyday file work needs no third-party packages at all.
This guide covers reading and writing plain text files, appending safely, working with CSV files as rows and as dictionaries, loading and saving JSON, and using pathlib for clean cross-platform paths. It also covers the errors you will actually meet, such as missing files and encoding problems, and how to handle them without crashing a script. If you already manipulate lists of records in memory, the techniques in our Python list comprehensions notes pair naturally with the CSV examples here, since a CSV file is essentially a list of rows waiting to be filtered and transformed.
Opening Files With the with Statement
The safest way to open a file in Python is the with statement. It creates a context that automatically closes the file when the block ends, even if an error occurs inside the block. Forgetting to close files can lock them on some systems and exhaust file handles in long-running programs, so treat with as the default, not an optional extra. The open() function takes a path and a mode: "r" for reading, "w" for writing from scratch, "a" for appending, and "x" for creating a new file that must not already exist.
# Write a text file (creates or overwrites)
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("First line of notes.\n")
file.write("Second line of notes.\n")
# Read the whole file back as one string
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Reading the snippet line by line: the first with opens “notes.txt” in write mode, which creates the file if it is missing and truncates it to empty if it already exists, a destructive behaviour to remember before pointing write mode at an important file. The encoding="utf-8" argument states the text encoding explicitly, which prevents surprises when a script runs on machines with different defaults and the file contains characters beyond plain ASCII. Inside the block, each write() call adds text; note that write() does not add a newline automatically, so the \n characters are included in the strings. When the block ends, the file is flushed and closed. The second block opens the same file in read mode and read() returns the entire content as a single string, ready to print or process.
Reading Text Files: read, readline, and Looping
Reading a whole file with read() is fine for small files, but large files should be processed line by line so only one line sits in memory at a time. A file object is iterable, so a plain for loop over it yields lines one by one. The readlines() method returns a list of all lines, and readline() returns a single next line, which suits manual step-by-step reading.
# Count lines and words without loading everything at once
line_count = 0
word_count = 0
with open("notes.txt", "r", encoding="utf-8") as file:
for line in file:
line_count += 1
word_count += len(line.split())
print("Lines:", line_count)
print("Words:", word_count)
# Read all lines into a list and strip newline characters
with open("notes.txt", "r", encoding="utf-8") as file:
clean_lines = [line.strip() for line in file]
print(clean_lines)
In the counting example, each line arrives with its trailing newline still attached, which does not matter for counting because split() breaks on any whitespace. Streaming like this keeps memory flat even for a log file with millions of lines. The second example uses a list comprehension to build a list of cleaned lines, calling strip() to remove the newline and any surrounding spaces, which is what you usually want before comparing or storing line values. Choosing between streaming and loading a list is a simple trade: stream when you process and discard, load a list when you need random access, sorting, or multiple passes over the same lines. For reading values out of a data file into dictionaries you can query by key, the patterns in our Python dictionary tips will help you structure the result.
Appending and Safe Writing Patterns
Append mode, "a", adds content to the end of a file without erasing what is already there, creating the file if needed. It is the right mode for logs, journals, and any running record. Write mode is the right choice for generated output that should be rebuilt fresh each run, such as a report. A related safety habit for important outputs is to write to a temporary file first and rename it when complete, so a crash mid-write never leaves a half-written main file.
from datetime import datetime
# Append a timestamped entry to a log file
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
entry = f"[{timestamp}] Backup finished successfully\n"
with open("app.log", "a", encoding="utf-8") as log:
log.write(entry)
# Writing many lines efficiently with writelines
report_lines = [
"Sales Report\n",
"============\n",
"Total orders: 128\n"
]
with open("report.txt", "w", encoding="utf-8") as report:
report.writelines(report_lines)
The log example builds a timestamp string with strftime, wraps it into an entry line using an f-string, and appends it. Running the script twice adds two entries rather than overwriting, which is exactly the behaviour a log needs. The writelines() method in the second part writes an iterable of strings in one call; despite the name, it does not add newlines either, so each string in the list includes its own \n. When you have many small writes to make, joining them or using writelines is tidier than dozens of separate write() calls, and printing to a file with print(..., file=f) is another convenient option for formatted lines.
Reading and Writing CSV Files
CSV files store tabular data as rows of comma-separated values, and Python’s csv module handles the quoting and escaping rules that make hand-splitting on commas unreliable, such as fields that themselves contain commas. The reader returns each row as a list of strings, while DictReader uses the header row to return each row as a dictionary keyed by column name, which is far more readable for wide files.
import csv
# Write a CSV file with a header row
rows = [
["name", "city", "score"],
["Aisha", "Lahore", "88"],
["Ravi", "Delhi", "92"],
["Lena", "Berlin", "79"]
]
with open("scores.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)
# Read it back as dictionaries
with open("scores.csv", "r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])
Passing newline="" when opening CSV files is the documented requirement: it lets the csv module control line endings itself and prevents blank extra rows on Windows. The writer example passes a list of lists to writerows, writing the header and data in one call; writerow writes a single row when you build output incrementally. On reading, DictReader consumes the first row as field names automatically, so each row dictionary can be accessed with row["name"] instead of fragile numeric indexes. Every value arrives as a string, so convert numbers explicitly with int() or float() before doing arithmetic. That conversion step is easy to forget and produces the classic bug where scores sort alphabetically, putting “100” before “79”. Spreadsheet exports and imports like this are the server-side counterpart to careful query thinking, where selecting the right columns matters just as much.
Filtering CSV Data Into a New File
import csv
with open("scores.csv", "r", newline="", encoding="utf-8") as source, \
open("top-scores.csv", "w", newline="", encoding="utf-8") as target:
reader = csv.DictReader(source)
writer = csv.DictWriter(target, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
if int(row["score"]) >= 85:
writer.writerow(row)
print("Filtered file written.")
This example opens two files in a single with statement, which guarantees both are closed at the end. The writer is created with the same field names the reader discovered, and writeheader() writes the header row to the new file. Each row is tested after converting its score to an integer, and only rows scoring 85 or more are written out. The result is a clean extract file. This read-filter-write shape is one of the most reusable patterns in practical Python scripting, and it works just as well at ten rows as at a hundred thousand, as long as you stream row by row rather than loading everything.
Reading and Writing JSON Files
JSON is the standard format for configuration files and API data, and Python’s json module converts between JSON text and native Python dictionaries and lists. json.dump writes an object to an open file, json.load reads one back, and their siblings dumps and loads work with strings in memory instead of files. The difference between the file and string versions is a single letter, so read calls carefully.
import json
config = {
"site_name": "SnipLedger",
"posts_per_page": 10,
"features": ["search", "tags", "rss"],
"maintenance": False
}
# Save JSON to a file with readable indentation
with open("config.json", "w", encoding="utf-8") as file:
json.dump(config, file, indent=2)
# Load it back
with open("config.json", "r", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded["site_name"]) # SnipLedger
print(loaded["posts_per_page"]) # 10 (a real number, not a string)
Unlike CSV, JSON preserves types: numbers come back as numbers, booleans as booleans, nested objects as dictionaries, and arrays as lists, so no manual conversion is needed after loading. The indent=2 argument pretty-prints the file with two-space indentation, making it easy to read and to diff in version control; omit it for compact files where size matters more than readability. Python dictionaries preserve insertion order, and json.dump writes keys in that order by default. If a file might not be valid JSON, because a user edited it by hand, wrap the load in a try block and catch json.JSONDecodeError so you can report the problem or fall back to defaults. Fetching JSON from the web and then saving it with this pattern is a common workflow, and the request side of it is covered in our Python requests examples.
Using pathlib for Cleaner Paths
The pathlib module represents paths as Path objects instead of plain strings. It joins paths with the / operator, which works on every operating system, and it offers quick methods like read_text() and write_text() for small files, plus useful checks such as exists() and properties like suffix and stem. For new code, pathlib is the recommended style.
from pathlib import Path
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)
file_path = data_dir / "greeting.txt"
# Quick write and read for small files
file_path.write_text("Hello from pathlib!\n", encoding="utf-8")
message = file_path.read_text(encoding="utf-8")
print(message)
print("Exists:", file_path.exists())
print("Name:", file_path.name)
print("Suffix:", file_path.suffix)
# List all text files in the folder
for txt_file in data_dir.glob("*.txt"):
print("Found:", txt_file)
The code creates a data folder with mkdir(exist_ok=True), which succeeds silently if the folder already exists, then builds the file path by joining with /, avoiding manual separator handling. The one-line write_text and read_text helpers open, operate, and close the file for you, which is perfect for small configuration or note files; for large files or line-by-line work, use Path.open() with a with block instead. The glob("*.txt") call lists matching files without extra imports. Running your scripts inside an isolated environment keeps these file tools and any added libraries tidy, as described in our Python virtual environments guide.
Handling File Errors Gracefully
File code fails in predictable ways: the file is missing, the folder is missing, permissions block access, or the content is not in the expected encoding. Catching FileNotFoundError specifically lets you give a useful message or create defaults instead of crashing with a traceback. Pair that with an existence check when creating defaults is the natural recovery, and let genuinely unexpected errors surface rather than hiding them behind a bare catch-all.
import json
try:
with open("settings.json", "r", encoding="utf-8") as file:
settings = json.load(file)
except FileNotFoundError:
print("No settings file found. Using defaults.")
settings = {"theme": "light", "posts_per_page": 10}
except json.JSONDecodeError:
print("Settings file is corrupted. Using defaults.")
settings = {"theme": "light", "posts_per_page": 10}
print(settings)
The two except blocks handle two different failures with the same recovery: fall back to a default settings dictionary so the program can continue. Keeping the handlers separate means log messages can say what actually went wrong, which helps debugging when a user reports a problem. A similar block around CSV reading can catch malformed rows. The guiding principle is to handle the errors you can predict at the exact place they can occur, provide a sensible fallback or a clear message, and avoid swallowing errors silently, because a script that fails quietly with wrong data is worse than one that stops loudly.
Conclusion
File handling in Python comes down to a few dependable habits. Open files with with so they always close, state the encoding explicitly, and pick the mode deliberately, remembering that write mode erases existing content. Read large text files line by line, use the csv module with newline="" for tabular data and convert numeric strings before calculating, and use json when types and structure matter. Prefer pathlib for building paths, and handle missing or corrupted files with specific exceptions and sensible defaults. With those patterns in place, reading and writing text, CSV, and JSON becomes routine, reliable groundwork for almost any script you build next.




2 thoughts on “Read and Write Files in Python: Text, CSV and JSON”