Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs

Dashboard
Notifications
Mark all as read
Q&A

Open file in script's own folder

+7
−0

I have a Python script that needs to access some data (or configuration) file in its very own folder. For example, say script.py does something like this:

with open('data.txt') as file:
    data = file.read()

The script will find the file, data.txt, if it is run in the terminal via python script.py from the same folder the script itself is in. But I want to call the script from any other folder, then with a relative or absolute path: python path/to/script.py. In which case it will fail to find the data file, raising FileNotFoundError.

How can I make sure the script finds the external file in its own folder?

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+7
−0

You can use the pathlib standard module with __file__ to make things simple.

from pathlib import Path

scriptFolder = Path(__file__).parent

with open(scriptFolder / 'data.txt') as file:
	data = file.read()
Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »