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}
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.pymy_name FOUNDED!
my_age FOUNDED!
C:\Users\Administrator\Desktop\document>
update_variable.py
my_name='phyger'my_age=88
OK,搞定!