I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?
itemIDScore = """SELECT * from anytime;"""
queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
for x in queryList:
fileName = x+".txt"
cur.execute(x) #This should execute the SQL command
print fileName #This should return "itemIDScore.txt"
I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.
Thanks!
I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:
queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']
Then you may access the value of variable from the variable name string using the globals()
function as:
for x in queryList:
fileName = "{}.txt".format(x)
data = globals()[x]
cur.execute(data)
As the globals()
document say:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments