0

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
newcoder
  • 5
  • 3
  • 1
    Either make a list to hold all of the strings you are printing which you can append to in each iteration of the loop or you can have a string variable which ```+=``` the string you are printing. – lc74 Aug 07 '19 at 17:37
  • See this answer on comparing string concatenation performance: https://stackoverflow.com/a/12169859/1008938 – Linuxios Aug 07 '19 at 17:38

2 Answers2

1

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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)
Adarsh Chavakula
  • 1,509
  • 19
  • 28