Read a txt/sql file as formatted string – f'{}' in Python

Question:

I have sql file which has table names as formatted string

query.sql

SELECT * FROM {table_name} WHERE LOAD_DT = '{load_date}'

How to read the sql file as f-string to pass it to pd.read_sql() method?

table_name = PRODUCTS
load_date = '15-08-2020'
# n other local variables

with open('query.sql','r') as file:
    sql_str = file.read()

Note: I do not prefer .format(table_name,load_date) or .format(**locals()) as I have a custom function to read various sql files and don’t want to send a param list of format variables every time, the reason being if the format list is huge it will be laborious while preparing the sql file with positional arguments and chances of mistakes are high

Asked By: rams

||

Answers:

You can use .format method of string:

sql_str = "SELECT * FROM {table_name} WHERE LOAD_DT = '{load_date}'"
sql_str.format(table_name="PRODUCTS", load_date="15-08-2020")

You can also pass all local variables into the .format method:

table_name = "PRODUCTS"
load_date = "15-08-2020"
sql_str.format(**locals())

It is also possible to achieve desired result using eval, which is quite dangerous:

table_name = "PRODUCTS"
load_date = "15-08-2020"
sql_str = "SELECT * FROM {table_name} WHERE LOAD_DT = '{load_date}'"
sql_str_f = f"f"{sql_str}""
result = eval(sql_str_f)
Answered By: Pavel Botsman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.