Open file in a relative location in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Opening a file with a relative path in Python is easy, but the meaning of "relative" is where people get tripped up. A path can be relative to the current working directory of the running process, or relative to the script file on disk, and those are not the same thing.
Relative to the current working directory
Python's built-in open() resolves a plain relative path from the process working directory.
This works if the program is launched from a directory where data/input.txt exists relative to the current shell location. It fails if the same script is launched from somewhere else.
That is why code that seems fine in an IDE can break in tests, cron jobs, containers, or another developer's machine.
Relative to the script file
If the file lives inside your project next to the script or package, build the path from __file__ instead. pathlib is the cleanest modern way to do that.
This version is robust because it does not care where the process was started. It anchors the path to the location of the script itself.
Decide which one you actually want
There is no universal best answer. Use the working-directory approach when the user is expected to run the program from a project root or pass paths relative to the current session. Use the __file__ approach when the file is part of the codebase and should always be found relative to the module.
That distinction is the important design point. Most "relative path" bugs come from mixing those two intentions without noticing.
Prefer pathlib for clarity
os.path still works, but pathlib.Path usually reads more clearly and composes better.
This is easier to read than string concatenation, and it is portable across operating systems.
Handle missing files explicitly
A relative path problem often shows up as FileNotFoundError. That should usually be handled close to the open call, especially when the file location is user-controlled or environment-dependent.
A clear error beats silently assuming the wrong directory and debugging later.
Packaged data versus ad hoc files
If the file is part of an installed Python package rather than just a loose project directory, direct path building may not be the best interface. In that case, package-resource tools are often safer because the file might not live on disk in the same shape as your source tree. Relative path code is best for ordinary project files, scripts, and local tooling.
Common Pitfalls
- Assuming
open("file.txt")is relative to the script file rather than the current working directory. - Building paths with string concatenation instead of
pathlibor proper path utilities. - Writing code that only works when launched from one specific directory.
- Ignoring
FileNotFoundErrorand making path bugs harder to diagnose. - Using
__file__for user-supplied paths that should really be resolved from the current execution context.
Summary
- Plain relative paths in
open()are resolved from the current working directory. - Files bundled with your script are often better addressed relative to
__file__. - '
pathlib.Pathis the cleanest way to build relative paths in modern Python.' - Decide whether the path should follow the process location or the script location.
- Most relative-path bugs are really about choosing the wrong reference point.
Related reading
- Open files in 'rt' and 'wt' modes
- open in Python does not create a file if it doesn't exist
- Open S3 object as a string with Boto3
- Open S3 object as a string with Boto3
- Openface Flask Wrapper Flask seems to be blocking a thread
- Operation on every pair of element in a list
- Optimizing Celery for third party HTTP calls
- Orange vs NLTK for Content Classification in Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.