0

I am using python-shell to call a python script from my nodejs server. The python script will open a file named myfile.txt and read its content: path = os.path.abspath("myfile.txt") f = open(path, 'r')

It runs normally when I execute the python code from Python command line but when I try to call it from Nodejs, turns out that the path became "path-to-nodejs-server/bin/myfile.txt" and I catch an error "No such file/ directory .."

How can I fix it?

2
  • is the file in the same directory as python? in which case you could replace os.path.abspath("myfile.txt") by os.path.join(os.path.dirname(__file__),"myfile.txt") Commented May 4, 2017 at 11:55
  • Yes the file is in the same directory as python code. Commented May 4, 2017 at 11:57

1 Answer 1

1
os.path.abspath("myfile.txt")

doesn't fix anything (unless you use os.chdir at some point, but that's not the case here)

The problem here is that you don't have a say on the current directory when your python script is run from nodejs.

but you know where your data file is stored relatively from your script.

Since __file__ contains the absolute path of your script you can locate your data file by:

os.path.join(os.path.dirname(__file__),"myfile.txt")
Sign up to request clarification or add additional context in comments.

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.