python对文件中的关键词查找替换,实现自动获取配置
1、目的
想对update_variable.py文件中的配置进行修改,数据通过系统接口自动获取
update_variable.py
my_name=‘null‘ my_age=18
2、代码
update_file.py
# name=phyger # line=‘my name: {name}‘ # new=line.replace(‘{name}‘,name) # print(new) # cur_abspath=os.path.abspath(__file__) import os cur_path=os.path.dirname(__file__) def change_words(old_str,new_str): file_data=‘‘ with open(cur_path+‘\\update_variable.py‘,mode=‘r+‘) as f: for line in f: if old_str in line: if isinstance(new_str,int): print(old_str+‘ FOUNDED!‘) line=old_str+‘=%d‘%(new_str) else: print(old_str+‘ FOUNDED!‘) line=old_str+‘=‘+‘\‘‘+new_str+‘\‘\n‘ file_data+=line f.close() with open(cur_path+‘\\update_variable.py‘,mode=‘w‘) as f: f.write(file_data) f.close() def change_name(new_name): change_words(‘my_name‘,new_name) def change_age(new_age): change_words(‘my_age‘,new_age) if __name__ == "__main__": new_name=‘phyger‘ change_name(new_name) new_age=88 change_age(new_age)
3、运行后结果
C:\Users\Administrator\Desktop\document>D:/Python37/python.exe c:/Users/Administrator/Desktop/document/update_file.py my_name FOUNDED! my_age FOUNDED! C:\Users\Administrator\Desktop\document>
update_variable.py
my_name=‘phyger‘ my_age=88
OK,搞定!
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16