首页 > 解决方案 > 如何将变量的值传递到另一个文本文件?

问题描述

我有包含 sql 查询的文本文件。运行一个文件“tb_exec_ns_call_pln.txt”后,我得到了两个日期,例如 2018-12-29 和 2019-03-29。

我只想使用 python 在其他文本文件(tb_exec_ns_call_actvty.txt)中传递这些日期。文本文件包含以下查询 -

SELECT a.nm as cycle_nm, 
a.start_dt as cycle_start_dt, 
a.end_dt as cycle_end_dt, 
a.terr as territory,sales_drctn, 
x_rating1,
c.jnj_id as jnj_id,
c.prsn_first_nm,
c.prsn_last_nm, 
plnnd_calls as rep_goal
FROM eureka.cycle_plan a, eureka.cycle_plan_trgt b, eureka.acct c
WHERE 
a.id = b.cycle_plan 
and b.acct = c.id 
and b.del_flg = 'N'
***and start_dt >= '2018-12-29'***
***and end_dt <= '2019-03-29'***
and substring(a.terr,1,6) in ('106-KS','106-PI','106-VO') 
and a.status = 'In_Progress_vod'
and a.del_flg = 'N'
and c.del_flg = 'N' and plnnd_calls > 0

我也写了python脚本。请指导我如何传递值。

path = "D:/Users/SPate233/Downloads/NS dashboard/tb_exec_ns_call_pln.txt"

sql_query_file = open(path, 'r')
sql_query1 = sql_query_file.read()
cur.execute(sql_query1)
res = cur.fetchall()
print(res)
print(type(res))
for val in res:
    print(val[1])
    print(val[2])

标签: python

解决方案


一种方法是硬编码一个字符串变量tb_exec_ns_call_actvty.txt,然后使用它str.replace来填写所需的信息。

前任:

SELECT a.nm as cycle_nm, 
a.start_dt as cycle_start_dt, 
a.end_dt as cycle_end_dt, 
a.terr as territory,sales_drctn, 
x_rating1,
c.jnj_id as jnj_id,
c.prsn_first_nm,
c.prsn_last_nm, 
plnnd_calls as rep_goal
FROM eureka.cycle_plan a, eureka.cycle_plan_trgt b, eureka.acct c
WHERE 
a.id = b.cycle_plan 
and b.acct = c.id 
and b.del_flg = 'N'
and start_dt >= 'START_DT'
and end_dt <= 'END_DT'
and substring(a.terr,1,6) in ('106-KS','106-PI','106-VO') 
and a.status = 'In_Progress_vod'
and a.del_flg = 'N'
and c.del_flg = 'N' and plnnd_calls > 0

代码:

path = "D:/Users/SPate233/Downloads/NS dashboard/tb_exec_ns_call_pln.txt"

with open(path) as sql_query_file:
    sql_query1 = sql_query_file.read()
    sql_query1 = sql_query1.replace("START_DT", '2018-12-29').replace("END_DT", '2019-03-29')

cur.execute(sql_query1)
res = cur.fetchall()

推荐阅读