문제

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.

도움이 되었습니까?

해결책 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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top