[英]how to read a value from text HI file using python?
I am new of python. 我是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 现在我想从下面的文件中读取这些值,并在python脚本中使用
host_name=host(host valuefrom text file ) same for all values. host_name = host(文本文件中的主机值)对于所有值都相同。
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: 您可以遍历
.txt
文件行并检查行是否有效,方法是检查行中是否存在=
,然后只需split()
行即可获得键和值对,如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.