1

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.