6

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?

0

2 Answers 2

6

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()
Sign up to request clarification or add additional context in comments.

6 Comments

module_path = os.path.dirname(os.path.realpath(__file__)) doesn't work for me. I need to use module_path = os.path.dirname(os.path.realpath("__file__")) instead.
That's strange, if I use "__file__" (using quotes) then i get the current working directory, not the module directory. What's more, using "__file__" gives me the same result as using "__some_random_string__". When you say that it doesn't work you mean that it throws an error?
In my case, "__file__" will also give the CWD, but __file__ simply throws NameError: name '__file__' is not defined.
Are you running it from python interactive shell? If so that's the problem.
Yes I am. I will try to run it in the normal mode.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.