0

I am trying to read a file in python. This is the code I am using:

# test script
import csv
import json
import os


def loadKeys(key_file):
    json_keys=open(key_file).read()
    data = json.loads(json_keys)
    return data["api_key"],data["api_secret"],data["token"],data["token_secret"]

KEY_FILE = 'keys.json'
print(os.listdir(os.path.dirname(os.path.realpath(__file__))))

api_key, api_secret, token, token_secret = loadKeys(KEY_FILE)

However it returns the following error

->print(os.listdir(os.path.dirname(os.path.realpath(__file__))))
['.DS_Store', 'keys.json', 'script.py', 'test.py']
->api_key, api_secret, token, token_secret = loadKeys(KEY_FILE)
IOError: (2, 'No such file or directory', 'keys.json')

Is there anything I am doing wrong?

0

1 Answer 1

1

the KEY_FILE has no path, so it defaults to looking in the current directory. You've listed the file in another directory, which is the result of:

os.path.dirname(os.path.realpath(__file__))

Use os.path.join:

path = os.path.dirname(os.path.realpath(__file__))
loadKeys(os.path.join(path,KEY_FILE))
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.