简体   繁体   中英

how to read a value from text HI file using python?

I am new of python.

i want to read a value from the text file.

for example my text fileis

textfile

host="host"
dbname="dbname"
uname="uname"
pwd="pwd"

now i want to read these values from the file like below and use in the python script

host_name=host(host valuefrom text file ) same for all values.

how can we read a file and how to read value alone from the text file.

Thanks in advance

You can just iterate over the .txt file lines and check if the line is valid, by checking if = is present in the line and then simply split() the line to get the key and value pair as:

kv_store = {}

with open("./file_path.txt", "r") as f:
    for line in f.readlines():
        # Strip any `\n` etc.
        line = line.strip()

        # Check if the line contains a key, value pair
        if len(line) > 0 and line.find("=") > 0:
            key, value = line.split("=", 1)
            kv_store[key] = value.strip('"')
print kv_store

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