0

I have a file in which i have set up my credentials; i have named it creds.py. The content looks something like this :-

{ "username": "abc",

  "password": "xyz" }

i am trying to import this in my main.py file

import json
import sys
import urllib.request
import urllib.response
import creds

def main():
    credentials = creds
    with open('credentials') as f:
        credentials = json.load(f)

But i keep getting this error message :-

 with open('credentials') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'credentials'

Can someone please point out what i am doing wrong? Any help will be appreciated.

2
  • 1
    Almost certainly the program is running from a different directory than the one the file is in. Use os.getcwd() (with import os) to figure out where your program thinks it is. Commented Apr 28, 2021 at 21:06
  • @NathanielFord i get /home/user/my-directory. This is where all the files are Commented Apr 28, 2021 at 21:09

2 Answers 2

1

The error is self explanatory. The file named credentials does not exist because you named the file creds.py. You need to change the line to:

with open('creds.py') as f:
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It worked!!! I'll accept this as an answer.
1

You created a module called creds by creating a file called creds.py. This module can contain variables, so in creds.py, instead of simply dumping the dictionary, assign it to a name.

creds.py

credentials = {"username": "[email protected]", "password": "13eun4c9t4"}

Then when you import creds, the import manager makes your dictionary accessible as creds.credentials

main.py

import creds

print(f"Username: {creds.credentials['username']}")
print(f"Password: {creds.credentials['password']}")

gives the output:

Username: [email protected]
Password: 13eun4c9t4

This way, you don't have to read json files and you can create more variables and functions in the same module that are related to credentials.

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.