newcoder
newcoder

Reputation: 5

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 lines into one variable for use later on in the code.

This is for a scheduling program which I want to be able read from a txt file so that users can edit it through GUI. However since it is a loop, defining it, then printing outside of the loop obviously only prints the last line and I cant figure out a way around it.

with open('schedule.txt') as f:
    for line in f:
        a,b,c = line.split(',')
        print('schedule.every().{}.at("{}").do(job, "{}")'.format(a, b, c))

Output is what I want however I cannot define the whole thing as one variable as needed.

Upvotes: 0

Views: 335

Answers (2)

Adarsh Chavakula
Adarsh Chavakula

Reputation: 1589

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 = []
with open('schedule.txt') as f:
    for line in f:
        a,b,c = line.split(',')
        variables.append([a, b, c])

print(variables)

Upvotes: 0

ForceBru
ForceBru

Reputation: 44838

Are you looking for something like this?

code = []
with open('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.

Upvotes: 1

Related Questions