MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Python Tutorials: Files Operations

Python handles files through the built-in open() function. The mode you pass to it decides whether you create, read, append to or overwrite a file, and os.remove() or pathlib deletes it. This page explains the modes shown in the diagrams above and gives a corrected, runnable version of the CRUD and JSON example code. It also covers the errors you are most likely to hit.


Python File Operations


Python file operations mind map: paths, open, read, write, search, file pointer, status, copy, move and delete

Python – Working with files

Working with files in Python: os module, urllib downloads, and reading and writing with open()

Python File Operations: Modes


Python open() function modes: r reads, a appends, w writes and overwrites, x creates a file
Table of Python file modes w, r, a, w+, r+, a+ and x with descriptions of each behavior

Python File Operations: Writing a file

Annotated Python code writing four user-entered names to names.txt in write mode, then closing the file

Python File Operations: CRUD



How Python file operations work

Every file operation follows the same three steps: open the file with open(path, mode), read or write through the returned file object, and close it. Closing matters because writes are buffered. Data may not reach the disk until the buffer is flushed, and an open file handle on Windows stops other processes, and your own script, from deleting or renaming the file.

The with statement closes the file automatically, even if an exception is raised. Use it in all new code instead of calling f.close() by hand, as most of the gist code above does.

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
# f is closed here, and the data is flushed to diskCode language: PHP (php)

Always pass encoding="utf-8" when you open a file in text mode. Without it, Python uses the platform's default encoding, so the same script can read a file correctly on Linux and fail with UnicodeDecodeError on Windows.

File modes reference

ModeMeaningIf file existsIf file is missing
rRead (default)Reads from the startFileNotFoundError
wWriteTruncates it to zero lengthCreates it
aAppendWrites go to the endCreates it
xExclusive createFileExistsErrorCreates it
r+Read and writeOpens without truncatingFileNotFoundError
w+Write and readTruncates itCreates it
a+Append and readWrites go to the endCreates it
bBinary, combined with the above (for example rb, wb)Works with bytes, no encodingSame as the base mode
tText (default), for example rtWorks with strSame as the base mode

Note: w never asks for confirmation. Opening an existing file in w mode wipes its contents immediately, even if you never call write(). Use x when you must not overwrite existing data.

Corrected CRUD example

The script below does the same create, read, update and delete steps as crud-file.py above. It runs cleanly from start to finish and can be run again without failing.

import os

os.makedirs("live", exist_ok=True)          # make sure the folder exists
target = os.path.join("live", "createfile.txt")

# CREATE: 'x' refuses to overwrite an existing file
try:
    with open(target, "x", encoding="utf-8") as f:
        f.write("First line.\n")
except FileExistsError:
    print(f"{target} already exists, skipping create")

# READ
with open(target, "r", encoding="utf-8") as f:
    print(f.read())

# UPDATE (append): adds to the end
with open(target, "a", encoding="utf-8") as f:
    f.write("Append this text.\n")

# UPDATE (overwrite): replaces everything
with open(target, "w", encoding="utf-8") as f:
    f.write("Overwrite existing data.\n")

with open(target, encoding="utf-8") as f:
    print(f.read())

# DELETE: safe because every handle is already closed
os.remove(target)
print("Exists after delete:", os.path.exists(target))Code language: PHP (php)

Expected output:

First line.

Overwrite existing data.

Exists after delete: FalseCode language: JavaScript (javascript)

The blank lines appear because each file ends with \n and print() adds a second newline. To print without the extra line, use print(f.read(), end="").

What was wrong in the original gist code

  • crud-file.py calls os.remove() but never runs import os, so the last line raises NameError: name 'os' is not defined.
  • "D:\\myfiles\welcome.txt" contains \w, which is an invalid escape sequence. It happens to work, but recent Python versions emit a SyntaxWarning. Use a raw string r"D:\myfiles\welcome.txt" or forward slashes "D:/myfiles/welcome.txt".
  • open("myfile.txt", "x") fails with FileExistsError the second time you run the script. The comment on the later "w" line says it creates a file "if it does not exist", but it also truncates an existing file.
  • Most files are opened and never closed. The last read of live/createfile.txt leaves the handle open before os.remove(), which raises PermissionError on Windows.
  • The comment above the demofile3.txt read says "after the appending". That file was overwritten with w, not appended to.
  • f.flush() immediately before f.close() does nothing extra, because closing a file always flushes it.
  • live/createfile.txt needs the live folder to exist. Mode a creates missing files but not missing directories.
  • In input.py, the variable input shadows Python's built-in input() function, and the script carries on even when the existence check says the file is missing.

Reading files efficiently

f.read() loads the whole file into memory. That is fine for small configuration files but a bad idea for multi-gigabyte logs. For those, iterate over the file object, which reads one line at a time:

with open("app.log", encoding="utf-8") as f:
    for line in f:                 # streams line by line
        if "ERROR" in line:
            print(line.rstrip())

# Other options
with open("app.log", encoding="utf-8") as f:
    first = f.readline()           # one line, including the trailing \n
    rest = f.readlines()           # list of remaining lines (loads all into memory)

# Binary files such as images or archives
with open("logo.png", "rb") as f:
    header = f.read(8)             # returns bytesCode language: PHP (php)

Checking paths with os and pathlib

The example above uses os.getcwd(), os.listdir() and os.path.isfile(). The standard-library pathlib module does the same jobs with a cleaner, object-oriented API and handles path separators on every operating system:

from pathlib import Path

cwd = Path.cwd()
print("Files in", cwd, [p.name for p in cwd.iterdir()])

p = Path("live") / "myfile.txt"   # / joins paths portably
print(p.exists(), p.is_file(), p.is_dir())

p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("quick write\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
p.unlink(missing_ok=True)          # delete; no error if already goneCode language: PHP (php)

Note: Relative paths such as live/myfile.txt are resolved against the current working directory, not the script's folder. If a script works from your IDE but not from cron or CI, build paths from Path(__file__).resolve().parent instead.

Corrected JSON read and write example

This version of input.py stops if the input file is missing and avoids shadowing built-in names. It produces the same output.txt.

import json
from pathlib import Path

src = Path("sample-programs/system/input.json")
dst = src.with_name("output.txt")

if not src.is_file():
    raise SystemExit(f"Input file not found: {src}")

with src.open("r", encoding="utf-8") as infile:
    data = json.load(infile)           # parse JSON into a dict

with dst.open("w", encoding="utf-8") as outfile:
    outfile.write(f"{data['name']}'s Hobbies:\n")
    for hobby in data["hobbies"]:
        outfile.write(f"{hobby}\n")

# Writing JSON back out
with src.with_name("copy.json").open("w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)Code language: PHP (php)

Resulting output.txt for the sample input.json:

Jason's Hobbies:
music
programming
games

Common errors and fixes

ErrorUsual causeFix
FileNotFoundErrorWrong relative path, or the parent folder is missingPrint os.getcwd(), use absolute paths, create folders with mkdir(parents=True, exist_ok=True)
FileExistsErrorMode x on a file that already existsCatch the exception or choose w/a deliberately
PermissionErrorNo access rights, or the file is still open (Windows)Close handles with with, check file ownership and permissions
IsADirectoryErrorThe path points to a folderCheck with is_file() before opening
io.UnsupportedOperation: not writableWriting to a file opened with rOpen with w, a or r+
UnicodeDecodeErrorFile encoding differs from the defaultPass the correct encoding=, or open in rb for binary data

Best practices

  • Use with for every file you open.
  • Always set encoding="utf-8" in text mode.
  • Prefer pathlib.Path over string concatenation for building paths.
  • Prefer trying the operation and catching FileNotFoundError over checking exists() first. Another process can delete the file between your check and your open().
  • For important files, write to a temporary file and then call os.replace(tmp, final). The replace is atomic on the same filesystem, so readers never see a half-written file.
  • Do not name variables input, file, open or list, because doing so hides built-in names.

For more practice, see the Python tutorials. File handling also comes up often in Python interview questions.

Frequently asked questions

What is the difference between w and a mode in Python?

w truncates an existing file to empty before writing, and a keeps the existing content and adds new data at the end. Both create the file if it does not exist.

How do I check if a file exists in Python?

Use os.path.isfile(path) or Path(path).is_file() from pathlib. When you are about to open the file anyway, it is more reliable to open it directly and catch FileNotFoundError.

How do I delete a file in Python?

Call os.remove(path) or Path(path).unlink(). Close any open handles to the file first. Pass missing_ok=True to unlink() if a missing file should not raise an error.

Why should I use with open() instead of open() and close()?

The with block closes the file automatically, even if an exception happens partway through. That way buffered data is written and the handle is released.

What is the difference between r+ and w+?

Both allow reading and writing. r+ requires the file to exist and keeps its contents. w+ creates the file or truncates an existing one to empty.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Elastic Tutorial: Elasticsearch 8.X Installation & CRUD in Linux

This page shows how to install Elasticsearch 8.x from the official tar.gz archive on Linux, start it as a non-root user, and connect over HTTPS with the…

Read More

Python Tutorials: Database operations using python – mysql

This tutorial connects Python to MySQL with the official mysql-connector-python driver and runs the full set of CRUD operations: create a database and table, then insert, read,…

Read More

AJAX Crud with laravel 5.8

sam MotoShare.in is your go-to platform for adventure and exploration. Rent premium bikes for epic journeys or simple scooters for your daily errandsโ€”all with the MotoShare.in advantage…

Read More

Elasticsearch Lab#1 – CRUD

Reference Sample Data & Query – https://github.com/devopsschool-demo-labs-projects/elasticsearch Rajesh Kumar I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world…

Read More

CRUD USING API IN Flutter (Part 1)

INTRODUCTION: In general, the use of JSON is used to communicate data from client to server and from server to client. In this article we are going…

Read More

Simple Ajax CRUD Application in Laravel

Step 1 – Create a fresh laravel projet First off all , create a project using following command given below – Change Directory to AjaxCrud folder Step…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x