0

Im trying to find out how to get certain data from a file in the easiest way possible. I have searched all over the internet but can't find anything. I want to be able to do this:

File.txt:

data1 = 1
data2 = 2

but i want to get only data1 like so,

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

Any Ideas, Thanks in advance.

user2213550
  • 151
  • 1
  • 1
  • 5

3 Answers3

2

You can do:

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

using map:

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
angvillar
  • 1,074
  • 3
  • 10
  • 25
  • you just want to take data1 string? or the value of data1 or both? – angvillar May 24 '13 at 01:39
  • You might even just use `str.strip` rather than `methodcaller('strip')` if you can guarantee that `line.split` will return a list of `str` instances. – icktoofay May 24 '13 at 02:35
0

If you know you only want data1 which is on the first line, you can do

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

The list comprehension is used to remove the whitespace from each string.

SethMMorton
  • 45,752
  • 12
  • 65
  • 86
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
kuafu
  • 1,466
  • 5
  • 17
  • 28
  • think that strip not removes the inner blank spaces so key == 'data1' fails cause it test key == 'data1 ' – angvillar May 24 '13 at 01:59
  • readline() just reads one line so if data1 is not in the first line you can retrieve it cause are not any iteration – angvillar May 24 '13 at 02:02
  • yes,you are right,but in the file maybe the user just want to the first line. – kuafu May 24 '13 at 02:06
  • the questions says that he wants to read data1 so to ensure that you can iterate over the lines of the file and check for the key – angvillar May 24 '13 at 02:09
  • in fact I think the data user want to read is a config file,so your map solution is better. – kuafu May 24 '13 at 02:26