读取txt文件并将变量添加到文本中 - Python

2024-05-14 14:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

为了简化我的一些代码,我决定将查询和HTML代码移到txt文件中。但是,出现了一个问题:我通常在代码中保留的大多数查询和HTML在中间都有变量。例如,我的代码中有:

count = 0
for x in reviewers:
    query = """select *
from mytable
where reviewer = """ + reviewers[count]
    cur.execute(query)
    count = count + 1
    #do more stuff

问题是,如何将查询或HTML代码保存在txt文件中,然后在字符串中间添加变量?你知道吗

谢谢!!你知道吗


Tags: 文件代码infromtxtforhtmlcount
2条回答

好的,这是我提出的解决方案,希望能有所帮助 因此,您可以将查询保存在表单中的文本文件中

SELECT * from %s where id = %d

一旦得到查询,就可以将变量放入其中。我假设我已经从文件中得到了查询。你知道吗

query = "SELECT * from %s where id = %d"
completeQuery=query% ('myTable', 21) 
print completeQuery

输出将是

SELECT * from myTable where id = 21

Reference

我仍然不知道你想要什么,这里有一个方法来读取一个文件,并在文本中添加一个变量名

query = ""
f = open("query_file",'r')     
query = f.read()    # read the query file into a string 
f.close()



for x in reviewers:
    query = query+reviewers[count]    # add variable name in the string assuming reviewers[count] gives a string
    cur.execute(query)
    count = count + 1
    #do more stuff

编辑

Python中的一个重要点是字符串是不可变的

如果要修改字符串,则必须创建一个新字符串

例如

query = "Select from Table"

你想让它Select Col from Table

以下是您的工作:

add_me = "Col"

new_string = query[:-10] + add_me + query[6:]

现在new_string字符串将有Select Col from Table

相关问题 更多 >

    热门问题