[英]How to Replace value of string in file with dictionary key-value using python script
[英]How to replace value in python script reading key from config file
我必须用python脚本中的值替换一个键,我正在从Config文件中读取密钥以创建一个URL。
例如: https:// xyz / prefix = dcm_accountclick_201903
配置文件:
go_req=https://xyz/prefix=dcm_accountclick_,yday_mnth
go_key=yday_mnth,
脚本:
yday_date = datetime.datetime.today() - timedelta(days=1)
last_date_fmt = datetime.datetime.strftime(yday_date,'%Y%m%d')
yday_mnth = last_date_fmt[:6]
reqItems = envvars.list['go_req'](here my envars script reads the go_req from config file)
reqKeys = envvars.list['go_key'](here my envars script reads the go_req from config file)
ur= reqItems.split(',')
keys= reqKeys.split(',')
req_url= ''
for i in ur:
for j in keys:
if (str(i) == str(j)):(here if yday_mnth in url matches with key then i will try to add the value which i am generating in script)
req_url += i(here eventhough it matches yday_mnth==yday_mnth am getting output as below)
https:// xyz / prefix = dcm_accountclick_ yday_mnth
所以我不确定为什么它没有采取变量yday_mnth的值,如果我给出如下,那么它的工作,但我希望我的脚本是通用的。
req_url + = yday_mnth
如果我理解正确,你想在reqItems
和reqKeys
之间匹配时输出yday_mnth
的值,然后将它附加到URL?
import datetime
yday_date = datetime.datetime.today() - datetime.timedelta(days=1)
last_date_fmt = datetime.datetime.strftime(yday_date,'%Y%m%d')
yday_mnth = last_date_fmt[:6]
reqItems = "https://xyz/prefix=dcm_accountclick_,yday_mnth"
reqKeys = "yday_mnth,"
ur= reqItems.split(',')
keys= reqKeys.split(',')
req_url= ''
for i in ur:
for j in keys:
if (str(i) == str(j)):
req_url += yday_mnth
print(req_url)
print(ur[0] + req_url)
输出:
201903
https://xyz/prefix=dcm_accountclick_201903
但更简单的实现方式是:
import datetime
yday_date = datetime.datetime.today() - datetime.timedelta(days=1)
last_date_fmt = datetime.datetime.strftime(yday_date,'%Y%m%d')
yday_mnth = last_date_fmt[:6]
reqItems = "https://xyz/prefix=dcm_accountclick_,yday_mnth"
print(reqItems.replace(",yday_mnth",yday_mnth))
输出:
https://xyz/prefix=dcm_accountclick_201903
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.