I am working on part of a Python project and the structure is like this:
project/some_folder/another_folder/my_work
.
In this folder, the file containing the code is run.py
.
In the same folder, I also have an input_file
from which I read some data, process it, and write the result to output_file
.
So in run.py
I have something like:
with open("input_file") as f:
do_something()
and
with open("output_file") as f:
store_the_result()
This works fine when I execute the code in project/some_folder/another_folder/my_work
.
However, when I go to project
and run the code using python -m some_folder.another_folder.my_work.run
, I will have trouble accessing the input file.
I tried to solve this problem by using the aboslute path to the files, but this will only work on my machine. If someone copies my code to his/her machine, he/she still needs to modify the hardcoded absolute path.
How to set the path to the files such that I can start the program either in the folder containing the input and output file, or run it as a module, and others will not need to modify the path to the file when running code on their machines?
You can get the path to the running module and then create a full path relatively from there:
import os
module_path = os.path.dirname(os.path.realpath(__file__))
input_path = os.path.join(module_path, 'input_file')
output_path = os.path.join(module_path, 'output_file')
with open(input_path) as f:
do_something()
with open(output_path) as f:
store_the_result()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With