Python - String Formatting or String Interpolation for text string from a file

Viewed 642

I would love to create a python script that loops through a bunch of files in a folder and replaces a bit of formatted text with a variable from the script.

for a (very simplified) example, a folder contains two files:

greeting.sql with the text

select greeting
from greeting_list
where name = {name}

and

credentials.sql with the text

select credentials
from credentials_list
where name = {name}

The python script could then pull in these text files, and interpolate the script, replacing the {name} variable in the text with a pre-defined variable, as name = 'Bob'.

Something like

fd = open('greeting.sql', 'r')
greeting = fd.read()
fd.close()

names = ['Jeff','Melanie','Nitin','Satya','Serena']

[run_sql(greeting.format(n)) for n in names] 

I usually use interpolated strings, as f'Greeting for {name} is {greeting}' so I'm highly confident my usage of .format() here doesn't make sense.

The point of this operation would be to allow analysts to update and maintain SQL code, while having a python script pull in the correct version of the script and run it with a variety of variables.

1 Answers

Well, the problem was very definitely that I was lazy with my .format() knowledge because f-strings seemed so much easier. The solution is quite simple:

With the same greeting.sql file above,

py_name = 'Bob'
print(greeting.format(name = py_name))

Works beautifully

Related