Reputation: 27
I have the following piece of code which I am trying to use to declare multiple variables at the same time:
for x in range(1, 15):
for y in range(1, 87):
strvar1 = "%s" % (x)
strvar2 = "%s" % (y)
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_" + str(strvar1) + "_" + str(strvar2) + ".txt", "r") as myurls:
myurls2_x_y = myurls.read().replace('\n', '')
When i added a print(myurls2_x_y)
and viewed the log the above code was opening each dynamic file path in sequence, then displaying and cleaning up the strings in the above text files as expected.
However, using this method in something like SAS (which is my main language) I was expecting each of the variable values to be retained as they have different names, i.e. i would expect to have variables myurls2_1_1
, myurls2_1_2
, myurls2_1_3
etc all declared.
The idea then is to pass them through a URL = declaration within some concurrent.futures
Python code that I have so that I can submit multiple URLS at once.
All that works fine apart from when the script comes to resolve the variables dynamically generated it gets to the first one, myurls2_1_1
and says that it isn't defined when it is.
Any ideas why that might be?
Thanks
Upvotes: 0
Views: 101
Reputation: 178125
One way is to use a dictionary using an x,y
tuple as the key:
myurls = {}
for x in range(1, 15):
for y in range(1, 87):
with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y),"r") as f:
myurls[x,y] = f.read().replace('\n', '')
Here's a example that I can run without your files to demonstrate lookup:
myurls = {}
TEMPLATE = r'C:\Python33\NASDAQ Stock Strings\NASDAQ_Config_File_{}_{}.txt'
def content(filename):
with open(filename) as f:
return f.read().replace('\n', '')
for x in range(1, 15):
for y in range(1, 87):
#myurls[x,y] = content(TEMPLATE.format(x,y))
myurls[x,y] = TEMPLATE.format(x,y)
print(myurls[1,5])
Output:
C:\Python33\NASDAQ Stock Strings\NASDAQ_Config_File_1_5.txt
Upvotes: 1