0

I have a file ref.py that depends on a text file ex.txt, that is in the same directory \home\ref_dir . So it works normally when I run the file ref.py, but if I try to import ref.py to another file work.py in a different directory \home\work_dir , I do the following

import sys
sys.path.append('\home\ref_dir')
import ref

But then I get an error, that the program cannot find ex.txt

How can I solve this issue without using absolute paths. Any ideas?

1
  • That's what python resources are for. You can import text together with your script/binary and open it as a resource inside your code, not just a file on real filesystem Commented Jul 30, 2023 at 21:32

1 Answer 1

1

Use the os module to get access to the current absolute path of the module that you're in, and then get the dirname from that

You would want to open ex.txt in your file like this.

import os

with open('%s/ex.txt' % os.path.dirname(os.path.abspath(__file__)) as ex:
    print ex.read()
Sign up to request clarification or add additional context in comments.

5 Comments

for some reason I get this: Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> os.path.abspath(file) NameError: name 'file' is not defined
Of course you would, what file would you consider "shell" to be? :-P Save your changes to a file, and run that file from python. So instead of python, and then typing file in the interpretor, do "python filename.py", and the file will have something to actually reference :)
__file__ is usually how I do this sort of thing too. FWIW if you want to distribute just .pyc files I think this will break (__file__ is basically a constant generated when the pyc file is), not sure why you'd want to do that though!
Also from file: Traceback (most recent call last): File "D:\Dropbox\python_libs\arabic_lib.py", line 37, in <module> path='%s/ex.txt' % os.path.dirname(os.path.abspath(file)) NameError: name 'file' is not defined
I think ____file____ for some reason doesn't work, what I need is basically something that can tell me the physical file location from which I am doing the import

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.