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.

2
  • 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. Commented Aug 7, 2019 at 17:37
  • See this answer on comparing string concatenation performance: stackoverflow.com/a/12169859/1008938 Commented Aug 7, 2019 at 17:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.