How To Make One Global Variable From A For Loop
So I have a for loop that when printing within the for loop prints exactly what I want since it prints for each line of the txt file. However I want to make all of those printed li
Solution 1:
Are you looking for something like this?
code = []
withopen('schedule.txt') as f:
for line in f:
a,b,c = line.split(',')
code.append('schedule.every().{}.at("{}").do(job, "{}")'.format(a, b, c))
Now code
is a list of strings. Then you can join them together in a single string like this:
python_code = ";".join(code)
Another way which may be easier to read is to define code = ""
and then append to it in the loop:
code += 'schedule.every().{}.at("{}").do(job, "{}");'.format(a, b, c)
Then you won't need to join
anything, but the output will have an unnecessary semicolon as the last character, which is still valid, but a bit ugly.
Solution 2:
Initiate an empty list before you open the file. Append the variables a
, b
and c
to the list as you read them. This would give you a list of lists containing what you need.
variables = []
withopen('schedule.txt') as f:
for line in f:
a,b,c = line.split(',')
variables.append([a, b, c])
print(variables)
Post a Comment for "How To Make One Global Variable From A For Loop"