DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

File Handling in Python: Read, Write, and Manage Files Safely

A practical guide to reading and writing files in Python, choosing modes safely, specifying text encodings, and using pathlib.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s built-in open() function to read or write a file, and wrap it in a with block so the file closes reliably. Choose a mode that matches your intent: r reads, w replaces existing contents, a appends, and x creates a new file only. For text, specify the known encoding—commonly "utf-8"—rather than relying on a machine’s default.

Read a text file with open()

open(path, mode, encoding=...) returns a file object. If you omit the mode, Python opens the file for text reading, equivalent to "r". This example makes both the mode and encoding explicit:

with open("notes.txt", "r", encoding="utf-8") as file:
    contents = file.read()

print(contents)

The with block closes the file when the block ends, including if an exception interrupts the work. Python’s official tutorial recommends using with for file objects; it avoids having to close the file manually.

Read one line at a time

For a file that may be large, iterate over it instead of loading all its contents into one string:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("notes.txt", encoding="utf-8") as file:
    for line in file:
        print(line, end="")

Iteration processes each line as it is read. The end="" argument prevents print() from adding an extra line break when the line already ends with one.

Choose a file mode that matches the task

Mode Purpose What happens to existing contents?
r Read a file. This is the default mode. Unchanged.
w Write from the start. Truncated: existing contents are erased when the file is opened for writing.
a Append new content. Kept; writing begins at the end.
x Create a new file exclusively. Opening fails if a file with that name already exists.
+ Allow both reading and writing when combined with another mode. Depends on the mode it is combined with.

Use t to indicate text mode and b for binary mode. Text mode is the default, so "r" and "rt" both mean text reading. Combine the letters when needed, such as "rb" for reading bytes.

Write a file without accidentally losing data

Warning: opening a file with "w" truncates it, erasing any previous contents. Use it only when replacement is intended:

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("First linen")

To add text without replacing what is already there, use "a":

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("Another linen")

Choose "x" when the file must be new and an existing file should not be overwritten:

with open("new-notes.txt", "x", encoding="utf-8") as file:
    file.write("Created oncen")

Text mode and binary mode are for different data

Mode Data exposed to your code Transformations Typical use
Text str Encodes strings on writing, decodes bytes on reading, and may translate line endings. Text files, such as notes or configuration files.
Binary bytes No text encoding or decoding and no newline translation. Images, executables, and byte-level processing.

For example, read an image in binary mode:

with open("photo.jpg", "rb") as file:
    image_data = file.read()

Do not pass encoding= in binary mode. Text newline conversion is useful for ordinary text but can alter data that must remain byte-for-byte intact.

Specify the encoding for text files

A text file’s encoding is a choice made by the file’s format or the program that created it; not every text file is UTF-8. When you know a file is UTF-8, state that explicitly:

with open("data.txt", encoding="utf-8") as file:
    text = file.read()

If you omit encoding, the default text encoding depends on the platform or locale, so code can behave differently across environments. The Python io documentation recommends specifying the encoding explicitly where appropriate. Python 3.10 and later also support encoding="locale" when using the current locale encoding is intentional; for a known UTF-8 file, use "utf-8" instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use pathlib for path-oriented file work

pathlib.Path makes it convenient to compose paths and provides methods for common file operations. For example, join a directory and filename with /, then read UTF-8 text:

from pathlib import Path

path = Path("data") / "notes.txt"
text = path.read_text(encoding="utf-8")

Path.open() works like the built-in open(). The whole-file convenience methods read_text() and read_bytes() return text and bytes respectively. Their write counterparts, write_text() and write_bytes(), open, write, and close the file—and overwrite an existing file—so take the same care as with "w".

Use open() when you want explicit mode control, line-by-line iteration, or a file object for a longer operation. Use pathlib when path composition or concise whole-file operations make the code clearer.

Official Python documentation

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.