Parsing files with python
My input file will be something like this
key "value"
key "value"
... the above lines repeat
What I am doing is read the contents of the file, fill the object with data, and return it. There are only a certain number of keys that can be present in the file. Since I am new to python, I feel like my code for reading the file is not that good
My code is like this
ObjInstance = CustomClass()
fields = ['key1', 'key2', 'key3']
for field in fields:
for line in f:
if line.find(field) >= 0:
if pgn_field == 'key1':
objInstance.DataOne = get_value_using_re(line)
elif pgn_field == 'key2':
objInstance.DataTwo = get_value_using_re(line)
return objInstance;
The "get_value_using_re" function is very simple, it searches for a string between double quotes and returns it.
I am afraid that I will have multiple ififif statements and I do not know if this is correct or not.
What am I doing here?
a source to share
The usual approach in Python would be something like this:
for line in f:
mo = re.match(r'^(\S+)\s+"(.*?)"\s*$',line)
if not mo: continue
key, value = mo.groups()
setattr(objInstance, key, value)
If is key
not the correct attribute name, on the last line key
you can use something like translate.get(key, 'other')
for some suitable dict instead translate
.
a source to share
I would suggest looking at a YAML parser for python. It can conveniently read a file very similar to it and enter it into a python dictionary. With a YAML parser:
import yaml
map = yaml.load(file(filename))
Then you can access it like a normal dictionary with a map [key] return value. The yaml files will look like this:
key1: 'value'
key2: 'value'
This requires all keys to be unique.
a source to share