简体   繁体   中英

How to read text file line by line and save values into variables in python

I want to read my parameter file line by line and save the values into a variable my parameter file look something like that

Parameter File

DBHOSTNAME=192.168.x.x
DBSID=SID
BEUSERNAME=username
BEUSERPASSWORD=password
HOSTPATHBE=path

Code

file = open('envparam.config')
    for line in file:
        fields = line.strip().split()
        print (fields[0])

So far I am able to read my parameter file but not able to store values into variables can anyone help me with this

If your file is consistent, this will store your info in a dictionary:

with open('envparam.config') as f:
    data = {}
    for line in f:
        key, value = line.strip().split('=')
        data[key] = value

You can then access it like this:

>>> data['DBSID']
SID

要创建一个以一行作为每个元素的列表,请使用带有“\\n”(换行符)的 .split() 方法

file = open('envparam.config').split('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM