2

I have a rather unusual problem. I wrote a python script which needs API keys. Since I don't want them floating around on the internet I created a seperate .json with the keys and added it to .gitignore. So far so good.

I wrote the program with VSCode and there I could execute it no problem. But when I try to use my program with the normal PowerShell it simply won't work. I get this error message when I run it on the external PS: FileNotFoundError: [Errno 2] No such file or directory: './master-folder/key.json'

I use a virtualenv, for the packages but that shouldn't affect anything (of course I activated it in PS). Here's the part of the code once again:

keys_fp = './master-folder/key.json'

keys = load(open(keys_fp, 'r'))

The folder structure is as follows:

.
├── programs
│   └── program.py
└── key.json
8
  • Add an os.getcwd() call in your script and see what it tells you. Commented Nov 9, 2018 at 20:17
  • @ritlew it outputs nothing, kinda strange Commented Nov 9, 2018 at 20:20
  • I'm sorry, I meant print(os.getcwd()) Commented Nov 9, 2018 at 20:24
  • 1
    This is why you shouldn't use relative paths. This doesn't appear to be a powershell problem at all. keys_fp = os.getcwd() + '\..\key.json' Commented Nov 9, 2018 at 21:07
  • 1
    @nerdlab as a best practice? always. Commented Nov 9, 2018 at 21:13

1 Answer 1

3

Based on your comments, your working directory is

E:\Git\master-folder\programs\

and inside your script, you're referencing

./master-folder/key.json

which resolves to

E:\Git\master-folder\programs\master-folder\key.json

but that doesn't exist. If you adjust your script to use the proper path, it should resolve your problem:

keys_fp = f'{os.getcwd()}\\..\\key.json'

According to this answer, you can access the script's root with the following:

import os
root = os.path.dirname(os.path.realpath(__file__))
keys_fp = f'{root}\\..\\key.json'
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.