Home > Back-end >  Extract a specific value from a text file
Extract a specific value from a text file

Time:03-13

total newbie here. I have a .txt file and I want to extract a specific value.... the .txt file is structure like this: { "animal": "Cat", "colour": "golden", ...and so on }

I can open and print he whole file ...... but how do I print just the "animal" plus its value which in this case is "cat" bit?

The file itself has hundreds of entries and I want to know how to extract and print all the "animal"s for example. Any help greatly appreciated.

CodePudding user response:

The text file you provided seems to be a dictionary itself. So I suggest you use ast module in order to change the format of this text file from string to a valid dictionary and then call animal key from this dictionary:

import ast
with open("myText.txt") as f:
  myFile = f.read()
  myDict = ast.literal_eval(myFile)
  print(myDict["animal"])

Output

Cat

Note that, I have named the text file myText.txt. It might be different in your machine, so change it to the valid path of your text file.

CodePudding user response:

You could use the json module to load the file contents which, from the sample you've given will result in a Python dictionary. So...

import json

with open('myfile.txt') as myData:
  myDict = json.load(myData)
  print(myData['animal'])

Output:

Cat
  • Related