Domanda

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.

È stato utile?

Soluzione 2

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

Altri suggerimenti

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top