Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set the path to input/output file?

Tags:

python

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?

like image 345
s9527 Avatar asked Jul 11 '17 08:07

s9527


1 Answers

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()
like image 111
Paco H. Avatar answered Nov 15 '22 00:11

Paco H.