Python's built-in os module lets a script work with the operating system: it can find and change the working directory, create and remove directories, rename and delete files, read environment variables and walk a directory tree. This page explains the functions listed below and fixes several of the gist examples that fail on current Python 3. It ends with a runnable lab script that you can use to practise.

File Operations using Python



About Python OS Module
The os module has many uses. We wonโt be covering everything that it can do. Instead, we will get an overview of its uses and weโll also take a look at one of its sub-modules, known as os.path. Specifically, we will be covering the following:
- os.name
- os.environ
- os.chdir()
- os.getcwd()
- os.getenv()
- os.putenv()
- os.mkdir()
- os.makedirs()
- os.remove()
- os.rename()
- os.rmdir()
- os.startfile()
- os.walk()
- os.path
Where os fits among Python's file tools
The os module is a thin layer over operating system calls. Its functions take path strings, return plain values and raise an OSError subclass when something goes wrong. Several other standard library modules overlap with it, and it helps to know which one to use for each job.
| Module | Use it for | Example |
|---|---|---|
os | Directories, renaming, deleting, environment variables, process information | os.makedirs("logs", exist_ok=True) |
os.path | Joining, splitting and checking path strings | os.path.join(base, "app.log") |
shutil | High-level copy, move and recursive delete | shutil.rmtree("build") |
pathlib | Object-oriented paths, usually the clearest choice in new code | Path("logs").mkdir(exist_ok=True) |
built-in open() | Reading and writing file contents | with open(p) as f: ... |
Note: os does not read or write file contents through file objects. Use the built-in open() for that. The low-level os.open(), os.read() and os.close() work with integer file descriptors, not with file objects.
Corrected versions of the gist examples
Several of the examples above raise errors on current Python 3. Each corrected version below includes a short note on what changed.
Reading a file with error handling (python-os-module8.py). The 'rU' mode was removed in Python 3.11 and now raises ValueError: invalid mode. In Python 3, universal newlines are the default in text mode, so 'r' is enough. IOError is now only an alias of OSError. Catch OSError and print the exception so the reason for the failure is visible.
filename = "GFG.txt"
try:
with open(filename, "r", encoding="utf-8") as f:
text = f.read()
print(text)
except OSError as e:
print(f"Problem reading {filename}: {e}")Code language: PHP (php)
Closing a file (python-os-module10.py). os.close() expects an integer file descriptor. Passing a file object raises TypeError. Either call file.close() (or better, use with), or use the low-level descriptor API from start to finish:
import os
# High-level: file object, closed automatically
with open("GFG.txt", "r", encoding="utf-8") as f:
print(f.read())
# Low-level: integer file descriptor, closed with os.close()
fd = os.open("GFG.txt", os.O_RDONLY)
try:
data = os.read(fd, 1024)
finally:
os.close(fd)
print(data.decode("utf-8"))Code language: PHP (php)
Renaming (python-os-module11.py). The original calls os.rename(fd, 'New.txt') twice. The second call raises FileNotFoundError because GFG.txt no longer exists. Rename once. Use os.replace() when you want to overwrite an existing destination. On Windows, os.rename() raises FileExistsError if the target exists, while os.replace() overwrites it on every platform.
import os
if os.path.exists("GFG.txt"):
os.replace("GFG.txt", "New.txt")
print("Renamed GFG.txt -> New.txt")
else:
print("GFG.txt not found")Code language: CSS (css)
os.popen (python-os-module9.py). os.popen() does not open a file. It runs its argument as a shell command and returns a pipe to that command. os.popen("GFG.txt", "w") tries to execute a program called GFG.txt, so the comment in the gist is wrong. The intended use looks like this, although subprocess.run() is the recommended replacement in new code:
import os
import subprocess
with os.popen("echo Hello") as pipe:
print(pipe.read().strip()) # Hello
result = subprocess.run(["echo", "Hello"], capture_output=True, text=True)
print(result.stdout.strip()) # Hello (on Linux/macOS)Code language: PHP (php)
Directory modes (python-os-module3.py and python-os-module4.py). On Linux and macOS, 0o666 gives a directory no execute bit, so nobody can cd into it or reach the files inside. Use 0o755 (or leave the default 0o777, which the process umask then reduces). On Windows the mode argument is largely ignored. Since Python 3.7, os.makedirs() applies mode only to the final (leaf) directory. Add exist_ok=True so the script can run again without raising FileExistsError.
import os
path = os.path.join("projects", "authors", "nikhil")
os.makedirs(path, mode=0o755, exist_ok=True)
print(f"Directory '{path}' ready")Code language: PHP (php)
Functions listed but not demonstrated above
The list above includes os.name, os.environ, os.getenv(), os.putenv(), os.startfile() and os.walk(), but the gists do not show them. Here they are in one example:
import os
print(os.name) # 'posix' on Linux/macOS, 'nt' on Windows
print(os.environ.get("HOME")) # dict-like mapping of environment variables
print(os.getenv("APP_ENV", "dev")) # returns the default if the variable is unset
# Preferred way to set a variable: updates os.environ AND child processes
os.environ["APP_ENV"] = "staging"
# os.putenv() changes the environment for child processes only;
# os.environ is NOT updated, so os.getenv() will not see the change
os.putenv("ONLY_FOR_CHILDREN", "1")
# Walk a tree top-down: yields (directory, subdirectories, files)
for root, dirs, files in os.walk("."):
dirs[:] = [d for d in dirs if d != ".git"] # prune directories in place
for name in files:
print(os.path.join(root, name))
# Windows only: open a file with its associated application
if os.name == "nt":
os.startfile("report.txt")Code language: PHP (php)
Note: os.startfile() exists only on Windows. On Linux and macOS, calling it raises AttributeError, so always guard it with os.name == "nt" or sys.platform checks.
Hands-on lab: a safe end-to-end run
This script works inside a temporary directory, so it cannot damage your real files. It covers most of the functions on this page. Save it as os_lab.py and run python3 os_lab.py.
import os
import tempfile
base = tempfile.mkdtemp(prefix="os-lab-")
print("Sandbox:", base)
os.chdir(base)
print("CWD:", os.getcwd())
os.makedirs(os.path.join("logs", "2026", "12"), exist_ok=True)
with open("app.txt", "w", encoding="utf-8") as f:
f.write("hello from os module\n")
print("Exists:", os.path.exists("app.txt"))
print("Size:", os.path.getsize("app.txt"), "bytes")
os.rename("app.txt", os.path.join("logs", "app.log"))
print("Listing:", sorted(os.listdir(".")))
for root, dirs, files in os.walk("."):
print(root, sorted(dirs), sorted(files))
os.remove(os.path.join("logs", "app.log"))
os.removedirs(os.path.join("logs", "2026", "12")) # removes 12, 2026, logs
print("After cleanup:", os.listdir("."))
os.chdir(os.path.expanduser("~"))
os.rmdir(base)
print("Sandbox removed:", not os.path.exists(base))Code language: PHP (php)
Expected output on Linux (the sandbox path will differ):
Sandbox: /tmp/os-lab-k3j9x2ab
CWD: /tmp/os-lab-k3j9x2ab
Exists: True
Size: 21 bytes
Listing: ['logs']
. ['logs'] []
./logs ['2026'] ['app.log']
./logs/2026 ['12'] []
./logs/2026/12 [] []
After cleanup: []
Sandbox removed: TrueCode language: JavaScript (javascript)
On Windows the size is 22 bytes, because text mode writes \n as \r\n, and the paths use backslashes. On macOS the CWD line may show a /private/... prefix because the temporary directory is a symlink.
Common errors and how to fix them
| Error | Typical cause | Fix |
|---|---|---|
FileNotFoundError | Path is wrong or relative to an unexpected working directory | Print os.getcwd(), build paths with os.path.join(), or use absolute paths |
FileExistsError | os.mkdir()/os.makedirs() on an existing directory, or os.rename() onto an existing file on Windows | Use os.makedirs(path, exist_ok=True) and os.replace() |
OSError: Directory not empty | os.rmdir() only removes empty directories | Delete the contents first, or use shutil.rmtree() with care |
PermissionError | No write permission, file open in another program (Windows), or a directory created with mode 0o666 | Check ownership and modes, close open handles, and create directories with 0o755 |
IsADirectoryError / PermissionError on os.remove() | os.remove() called on a directory | Use os.rmdir() or shutil.rmtree() for directories |
TypeError from os.close() | Passing a file object instead of an integer descriptor | Call f.close() or use with open(...) |
ValueError: invalid mode: 'rU' | Python 2 era mode string on Python 3.11+ | Use 'r' |
Best practices
- Build paths with
os.path.join()orpathlib.Pathinstead of hard-coding separators or drive letters such asD:/Pycharm projects/. That keeps scripts portable between Windows and Linux CI runners. - Use
with open(...)so files are closed even when an exception occurs. - Prefer
exist_ok=Trueandos.replace()so scripts can run more than once without failing (idempotent automation). - Avoid
os.chdir()in libraries and long-running services. It changes global state for the whole process. Pass explicit paths instead. - Never pass untrusted input to
os.popen()oros.system(), because both run through a shell. Usesubprocess.run()with an argument list. - Read configuration and secrets through
os.environ.get()with a sensible default or a clear error. Do not print secret values to logs. - Double-check the target before calling
shutil.rmtree()or recursive delete loops. Resolve the absolute path and log it before deleting.
Quick os to pathlib reference
Many teams now write new code with pathlib. Both styles work, and these are the equivalents of the calls covered on this page:
| os / os.path | pathlib |
|---|---|
os.getcwd() | Path.cwd() |
os.path.join(a, b) | Path(a) / b |
os.path.exists(p) | Path(p).exists() |
os.path.getsize(p) | Path(p).stat().st_size |
os.makedirs(p, exist_ok=True) | Path(p).mkdir(parents=True, exist_ok=True) |
os.rename(a, b) | Path(a).rename(b) |
os.remove(p) | Path(p).unlink() |
os.rmdir(p) | Path(p).rmdir() |
os.listdir(p) | list(Path(p).iterdir()) |
Frequently asked questions
What is the difference between os.mkdir() and os.makedirs()?
os.mkdir() creates a single directory and fails if its parent does not exist. os.makedirs() also creates any missing parent directories, and with exist_ok=True it does not fail if the directory already exists.
How do I delete a directory that is not empty in Python?
os.rmdir() only removes empty directories. To delete a directory and everything in it, use shutil.rmtree(path), and confirm the path first because the deletion cannot be undone.
Why does os.putenv() not change os.getenv()?
os.putenv() changes the environment that child processes inherit but does not update the os.environ mapping, which is what os.getenv() reads. Assign to os.environ["NAME"] instead, which updates both.
Should I use os.path or pathlib?
Both are supported and use the same operating system calls underneath. pathlib usually reads more clearly in new code, while os.path appears in a lot of existing scripts and is still useful for working with plain strings.
How can I check if a file exists before opening it?
Use os.path.exists(path) or os.path.isfile(path). Another process can still remove the file between the check and the open, so wrapping open() in try/except FileNotFoundError is the more reliable pattern.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- Top 50 Python Interview Questions and Answers
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals