'Extract a specific value from a text file

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.



Solution 1:[1]

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.

Solution 2:[2]

If you have "animal": ... in separated lines then you could read line by line and check if "animal" in line and later split(":") and remove " ", to get only text Cat, etc.

Minimal working example. I use io only to simulate file but you should use open()

text = '''{
"animal": "Cat",
"colour": "golden",
#...and so on
}
{
"animal": "Dog",
"colour": "black",
#...and so on
}
'''

import io

#f = open(filename)
f = io.StringIO(text)

for line in f:
    line = line.strip(' \n,')  # remove spaces, tabs but also `,`
    
    #if 'animal' in line:            # it get `animal` in any place - ie. 'small animals'
    if line.startswith('"animal"'):  # it get only "animal" (with `" "`) at the beginning of line
        parts = line.split(':')
        print(parts[1].strip(' "'))

Result:

Cat
Dog

But this way you get only value for animal and you would need much more code to get all values in records - so it would need more code to display colour only for Cat.


But your data looks similar to JSON so maybe you have all records inside [ ] and with , between records - like

[
{
"animal": "Cat",
"colour": "golden",
#...and so on
},
{
"animal": "Dog",
"colour": "black",
#...and so on
}
]

and then you could use module json to get it as list with dictionares and use for-loop to check every record and get animal. And it could be simpler to get other values - ie. get colour only for Cat.

text = '''[
{
"animal": "Cat",
"colour": "golden"
},
{
"animal": "Dog",
"colour": "black"
}
]
'''

import io
import json

#f = open(filename)
f = io.StringIO(text)

data = json.load(f)

for record in data:
    print(record['animal'])
    if record['animal'] == 'Cat':
        print('  colour:', record['colour'])

Result:

Cat
  colour: golden
Dog

If you create this file with records then you could use module json to write data.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amirhossein Kiani
Solution 2