0

我试图找出如何以最简单的方式从文件中获取某些数据。我在互联网上搜索过,但找不到任何东西。我希望能够做到这一点:

文件.txt:

data1 = 1
data2 = 2

但我只想像这样得到data1,

p = open('file.txt')
f = p.get(data1)
print(f)

任何想法,在此先感谢。

4

3 回答 3

2

你可以做:

with open("file.txt", "r") as f:
    for line in f:
        key, val = line.split('=')
        key = key.strip()
        val = val.strip() 
        if key == 'data1':  # if data1 is not the first line
            # do something with value and data

使用地图:

from operator import methodcaller
with open("file.txt", "r") as f:
    for line in f:
        key, val = map(methodcaller("strip", " "), line.split('='))
        if key == "data1":
             # do something with value and data
于 2013-05-24T01:35:18.383 回答
0

如果你知道你只想要data1第一行,你可以做

with open('file.txt', 'r') as f:
    key, val = tuple(x.strip() for x in f.readline().split('='))

列表推导用于从每个字符串中删除空格。

于 2013-05-24T01:45:40.620 回答
0
with open("file.txt", "r") as f:
        key, val = f.readline().split('=')
        if key.strip() == 'data1':  # if data1 is not the first line
            # do something with value and data
于 2013-05-24T01:58:14.860 回答