Filtering Data in a Text File with Python
I'm new to Python (like Zygote new), and it's just to supplement another program but what I need is I have a text file that's a group of items for a game and it is formatted so:
[1]
Name=Blah
Faction=Blahdi开发者_Go百科ddly
Cost=1000
[2]
Name=Meh
Faction=MehMeh
Cost=2000
[3]
Name=Lollypop
Faction=Blahdiddly
Cost=100
And I need to be able to find out what groups (the numbers in brackets) have matching values.
So if I search Faction=Blahdiddly Group 1 & 3 will come up.
I unfortunately have NO idea how to do this.
Can anyone help?
As Senthil indicates, ConfigParser is what you really want to read such a file. However, it doesn't provide an easy way to filter things the way you want. You can do it (get a list of the sections, see if the key is in each section, and if so, whether it has the desired value, and if so, record the section), but something like this might be more straightforward.
datafile = open("datafile.txt")
section = None
found = []
match = set(["Faction=Blahdiddly"]) # can be multiple items
for line in datafile:
line = line.strip()
if line.startswith("[") and line.endswith("]"):
section = line.strip("[]")
elif line in match:
found.append(section)
print found
Have you looked at ConfigParser module? The text file you describe seems to be something which ConfigParser can recognize out of box. Here is an example to get you started.
精彩评论