How do I set the path to the I / O file correctly?

I'm working on part of the Python project, and the structure is as follows: project/some_folder/another_folder/my_work

.

In this folder there is a file with the code run.py

. In the same folder I also have input_file

one 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 great when I execute the code in project/some_folder/another_folder/my_work

. However, when I go to project

and run the code with python -m some_folder.another_folder.my_work.run

, I have problems accessing the input file. I tried to solve this 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, they still need to change the absolute hardcoded path.

How do I set the file path so that I can run the program either in the folder containing the input and output files, or run it as a module, and others won't need to change the file path when they run the code on their machines?

+3


source to share


2 answers


You can get the path to the running module and then create the full path relative 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()

      

+3


source


If you do not explicitly specify the "input_file" path, Python assumes that it is in the current directory where you are executing your Python script. The answer given by Paco H should fix the problem.



0


source







All Articles