对于喜欢偷懒的我来说,重复同样的工作是很令人头疼的事情,总想找到一条捷径,最好是一劳永逸。本次跟大家分享的是对log日志,json文件以及配置文件的解析,读取。
首先是log日志的读写:
读取数据:
f = open("spring05注意事项.txt",mode='r',encoding='utf-8')
line = f.readline()
while line :
print("行内容:{%s}"%line)
line =f.readline()
f.close()
运行结果如下图:
写:
#encoding:utf-8
str1="testcase001,pass,{}\n"
str2="testcase001,pass,{}\n"
str3="testcase001,failed,{断言错误}\n"
str4="testcase001,pass,{}\n"
with open("test_result.txt",mode="w",encoding="utf-8") as out_file:
out_file.write(str1)
out_file.write(str2)
out_file.write(str3)
out_file.flush()
out_file.close()
运行结果:
思想:当我们每隔一段时间去查看日志,日志很大的时候怎么办,里面的错误我们不能够逐行查看,此时,你的优势就来了,首先,将日志读取,然后找出看包含error的行,将他们读取出来,写到一个新的log.txt文件中。
2.json文件
读:
import json
with open("test_ressult.json",mode="r",encoding="utf-8") as json_file:
json_dic = json.load(json_file)
print(json_dic["test3"]["v"])
写:
#encoding:utf-8
import json
json_dic={"a":123,"sd":"erwe"}
with open("test_output.json",mode="w",encoding="utf-8") as json_file:
json.dump(json_dic,json_file,ensure_ascii=False)
3.ini配置文件
读:
import configparser
cfg=configparser.ConfigParser()
cfg.read("cfg.ini",encoding='utf-8')
all_section=cfg.sections()
print("所有节点:{%s}"%all_section)
mysql_info=cfg.items("mysql")
print("mysql节点下所有的配置:{%s}"%mysql_info)
mysql_username=cfg.get("mysql","username")
print("mysql的用户名是:{%s}"%mysql_username)
写:
import configparser
cfg=configparser.ConfigParser()
cfg.add_section("test01")
cfg.set("test01","testcase01","pass")
cfg.set("test01","testcase02","False")
cfg.set("test01","testcase03","pass")
cfg.set("test01","testcase04","False")
cfg.add_section("test02")
cfg.set("test02","testcase05","pass")
cfg.set("test02","testcase06","False")
cfg.set("test02","testcase07","pass")
cfg.set("test02","testcase08","False")
cfg.write(open("test.ini",mode="w",encoding="utf-8"))