Search code examples
pythonfileparsingtwitteraccess-token

Read Tokens from config file in Python


Im new in the world of Python and i have a question for you:

Im using the Python Twitter Tools for streaming and storing tweets and want to read the Access Tokens from a different file (config.py) with the format..:

from twitter import *

WORLD_WOE_ID = 1
ARGENTINA_WOE_ID = 23424747

CONSUMER_KEY = "xxxxxx"
CONSUMER_SECRET = "xxxxx"
ACCESS_TOKEN_KEY = "xxxxx"
ACCESS_TOKEN_SECRET = "xxxxx"

How can i read this file and parse only the tokens what i need?

I tried to use "file.readline()" but that command brings me the full line (included "CONSUMER_KEY = ..." etc..) and i only need the key between quotation marks :S

Thank you and sorry for my bad English !


Solution

  • You can simply import the variable.

    Save this file as config.py

    Then you can import the consumer key as follows:

    from config import CONSUMER_KEY
    
    print(CONSUMER_KEY)
    >> XXXXXXX
    

    Make sure the folder containing these files has an __init__.py file in it.

    Better practice would be to import it from the folder that it resides in.

    from folder_name.config import CONSUMER_KEY
    

    You can also, import it in the __init__.py and then get it with

    from folder import CONSUMER_KEY