Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
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 ...
#2: Post edited
- 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:
- ```python
- 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?
- 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:
- ```python
- 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?
#1: Initial revision
Open file in script's own folder
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: ```python 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?