开发者

Delineating a Read File

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 .t开发者_如何学运维xt 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?


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 :)


for line in open("file")
    key, value = line.strip().split("=")
    key=key.strip() 
    value=value.strip() 
    do_something(key,value)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜