Read file with Python while passing arguments

Viewed 141

I'm trying to read a file with this argument {year} inside it.

Inside this file there is this string: SELECT * FROM TABLE WHERE YEAR = {year}

I'd like to read this file with Python f-strings to use the query after.

The expected result looks like this: SELECT * FROM TABLE WHERE YEAR = 2019

I tried this:

year = 2019
with open("test.sql") as query_file:
     query = query_file.read()
print(query)

But the output was SELECT * FROM TABLE WHERE YEAR = {year} instead of SELECT * FROM TABLE WHERE YEAR = 2019

I have no idea how I can put the year variable to replace the {year} inside the file.

1 Answers

Use str.format to replace the {year}.

f-strings are literals and must be an expression. Python will not replace data in string, just because there is a variable of the same name in the bracket notation.

query = 'SELECT * FROM TABLE WHERE YEAR = {year}'
query.format(year=2019)

Edit:
To replace values in a SQL query it's better and more secure to use prepared statements like:

c = db.cursor()
year = 2019
c.execute("SELECT * FROM TABLE WHERE YEAR = %s;", (year,))

See also the examples of MySQLdb

Related