Python Forum

Full Version: getting information from a text file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
so i have a text file with api keys and urls.

text file looks like this
api_key = "xxxxxxxxxxxxxxxxxxx"
url = "xxxxxxxxxxxxxxxxxxxx"

is it possible to open the text file and just read what the api_key equals with out reading the whole line?
You can probably call seek on the file object to move the file pointer to the right place before reading. Why though? What's wrong with reading the line? If you're making your own config file format, you could of course use something that exists already (JSON, YAML, ...).
split each line on the " delimiter and print 2nd item

import os


def main():
    os.chdir(os.path.abspath(os.path.dirname(__file__)))
    with open('atextfile.txt') as fp:
        for line in fp:
            line = line.strip()
            parts = line.split('"')
            print(parts[1])


if __name__ == '__main__':
    main()
(Nov-16-2020, 01:39 AM)Nickd12 Wrote: [ -> ]is it possible to open the text file and just read what the api_key equals with out reading the whole line?
How would you know where to start reading and what chunk size to read?

If you can alter the file format - remove the quotes and use configparser module.

Or do as @ndc85430 suggest - use more suitable format.
ive tried going the json route still learning how to work with json maybe someone can tell me why im get error

{
"text_to_speech": [
{
"api_key": "xxxxxxxxxxxxxxxxxx",
"api_url": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
],
"speech_to_text": [
{
"api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"api_url": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
]
}



with open("ibm_watson_speech.json") as json_file:
    data = json.load(json_file)
    print(data['text_to_speech']['api_key'])
I don't see any error in your posting. Can you show the complete text of the error or any other output?
try post 3
this is the error

print(data['text_to_speech']['api_key'])
TypeError: list indices must be integers or slices, not str

that is the full code
If we look at your JSON with the structures formatted:
{
  "text_to_speech": 
  [
    {
      "api_key": "xxxxxxxxxxxxxxxxxx",
      "api_url": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
  ],
  "speech_to_text": 
  [
    {
      "api_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "api_url": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
  ]
}
You can more easily see that the api_key element isn't directly inside the "text_to_speech" dictionary, it's inside a list within. So you'd need to either get rid of that enclosing list, or you'd have to access it by asking for the first element in that list:

>>> data["text_to_speech"]["api_key"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> data["text_to_speech"][0]["api_key"]
'xxxxxxxxxxxxxxxxxx'