Home > Enterprise >  Read a txt/sql file as formatted string - f'{}' in Python
Read a txt/sql file as formatted string - f'{}' in Python

Time:10-16

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

CodePudding user response:

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)
  • Related