views:

63

answers:

3

Not really too sure how to word this question, therefore if you don't particularly understand it then I can try again.

I have a file called example.txt and I'd like to import this into my Python program. Here I will do some calculations with what it contains and other things that are irrelevant.

Instead of me importing this file, going through it line-by-line and extracting the information I want.. can Python do it instead? As in, if I structure the .txt correctly (whether it be key / value pairs seperated by an equals on each line), is there a current Python 'way' where it can handle it all and I work with that?

+4  A: 
with open("example.txt") as f:
    for line in f:
        key, value = line.strip().split("=")
        do_something(key,value)

looks like a starting point if I understand you correctly. You need Python 2.6 or 3.x for this.

Another place to look is the csv module that can parse comma-separated value files - and you can tell it to use = as a separator instead. This will abstract away some of the "manual work" in that previous example - but it seems your example doesn't especially need that kind of abstraction.

Another idea:

with open("example.txt") as f:
    d = dict([line.strip().split("=") for line in f])

Now that's concise and pythonic :)

Tim Pietzcker
Ah, interesting. Yes I think that will do the job. I'm trying to seperate these key / value pairs however some of the values are seperated by commas... but I'll be able to handle that! Thank you very much indeed.
day_trader
I added a `.strip()` method call to get rid of newlines - and another way to do everything in one line via a list comprehension.
Tim Pietzcker
Fantastic! I was just playing around with a couple of String manipulations when I seen your comment! Cheers!
day_trader
You might be happier with `line.strip().partition('=')`. It can handle a value that has an '=' in it.
S.Lott
A: 
for line in open("file")
    key, value = line.strip().split("=")
    key=key.strip() 
    value=value.strip() 
    do_something(key,value)
ghostdog74
A: 

There's also another method - you can create a valid python file (let it be a list, dict definition or whatever else), read its content using

f = open('file.txt', r)
content = f.read() #assuming file isn't too long

And then just parse it:

parsedContent = eval(content)

You can pass any environment to eval (see docs), so it might not have access to your globals and locals. This is evil and wrong, but in small program that won't be distributed and won't get 'file.txt' from network or from so called malicious user - you can use it.

Abgan