0

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=Blahdiddly
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?

1
  • Do you have any control over the file format used? If you just want to load data and share it between progs, XML may be for you. If you want to do searching and sorting, you might want to start looking at a database like SQlite instead. Commented Jan 14, 2011 at 6:36

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

then you do this "elif line in [match1,match2,match3]:"
... or a set, which is even better.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.