File handling
Open, read, and write files with Python
Programs often need to read information from files and save results back to disk. Python has file handling built in, so you don't need to install anything to work with text files.
Opening a file
Use open() inside a with block. The with block closes the file for you automatically when it ends, even if an error happens.
with open("notes.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)
print(len(text), "characters")"notes.txt": the path to the file."r": the mode (read).encoding="utf-8": handles accents, emoji, and other special characters correctly.
encoding="utf-8". Without it, Windows may use a different encoding and you'll see strange characters or a UnicodeDecodeError.File modes
| Feature | Meaning | If the file exists | If it doesn't exist |
|---|---|---|---|
| "r" | Read | Reads it | FileNotFoundError |
| "w" | Write | Erases and overwrites it! | Creates it |
| "a" | Append | Adds to the end | Creates it |
Ways to read
# The whole file as one string
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
# A list of lines
with open("notes.txt", encoding="utf-8") as f:
lines = f.readlines()
# Line by line (best for very large files)
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print(line.strip()).strip() removes the newline character (\n) at the end of each line.
Writing to a file
Use "w" to create or replace a file, and "a" to add to the end of it. write() doesn't add a newline for you, so include \n yourself.
with open("summary.txt", "w", encoding="utf-8") as f:
f.write("Python is great for AI.\n")
f.write("Files are easy to work with.\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("Program ran successfully\n")Writing a list of lines
fruits = ["apple", "banana", "cherry"]
with open("fruits.txt", "w", encoding="utf-8") as f:
for fruit in fruits:
f.write(f"{fruit}\n")Where Python looks for files
A plain filename like "notes.txt" is looked up in the folder your terminal is in, which isn't always the folder your script is in. Keep data files in a data folder and build paths with pathlib.
my-project/ ├── data/ │ └── notes.txt └── main.py
from pathlib import Path
DATA_DIR = Path(__file__).parent / "data"
file_path = DATA_DIR / "notes.txt"
if file_path.exists():
text = file_path.read_text(encoding="utf-8")
print(text[:200])
else:
print(f"File not found: {file_path}")Path objects also have the shortcuts read_text() and write_text() for reading or writing a whole file in one line. See Python paths for more on how paths work.
Handling missing files
Use try/except so a missing file shows a friendly message instead of crashing your program.
try:
with open("settings.txt", encoding="utf-8") as f:
settings = f.read()
except FileNotFoundError:
print("settings.txt not found, using defaults.")
settings = ""Reading PDFs
PDFs aren't plain text, so open() can't read them directly. Install the pypdf package and extract the text from each page.
pip install pypdffrom pypdf import PdfReader
reader = PdfReader("data/report.pdf")
pages = []
for page in reader.pages:
pages.append(page.extract_text() or "")
text = "\n".join(pages)
print(f"{len(reader.pages)} pages, {len(text)} characters")extract_text() returns nothing for them. Text-based PDFs work fine.Common mistakes
FileNotFoundError: the path is relative to your terminal's folder, not the script. UsePath(__file__).parent.- Opening with
"w"when you meant"r"or"a"."w"erases the file immediately. - Forgetting
encoding="utf-8". - Forgetting
\ninwrite(), so everything ends up on one line.
What's next?
Plain text is great, but structured data needs a structured format. Next you'll learn JSON.