-1

So I have some user inputs, which I saved in lists and then wrote into a text file line by line like this:

txtfile1 = open("Input progression data.txt", "w+")
txtfile1.write(', '.join([str(item) for item in prog_input]) + '\n')
txtfile1.write(', '.join([str(item) for item in progmt_input]) + '\n')
txtfile1.write(', '.join([str(item) for item in mt_input]) + '\n')
txtfile1.write(', '.join([str(item) for item in ex_input]) + '\n')
txtfile1.close()

I also have this list:

result1 = ["Progress", "Progress(MT)", "ModuleRT", "Exclude"]

I am trying to print each item from result1 followed by the corresponding line from my text file. The output should look like this:

Progress: 120, 0, 0 
Progress(MT): 100, 0, 20 
ModuleRT: 80, 20, 20 
ModuleRT: 60, 0, 60 
Exclude: 40, 0, 80

This is what I have so far, it only printthe list items in order:

def c(list1):
    for i in range (len(list1)):
        print(list1[i], ":" ,end="" )
        with open("Input progression data.txt") as file:
            for item in file:
                print(item+ '\n')
                    
c(result1)
mapf
  • 1,906
  • 1
  • 14
  • 40
  • Sorry, I can't understand what you're asking. Please try to create a https://stackoverflow.com/help/minimal-reproducible-example, by showing the *exact, complete* input as well as the exact, complete desired output. You should also try to write code that produces that output - at least try to have code that puts all the desired pieces of data into the file, and then if they're in the wrong order or otherwise wrongly formatted, you can *show that result* and ask a *specific* question about the problem. – Karl Knechtel Nov 29 '21 at 15:34
  • That said: I'm **guessing** that what you're stumbling on is trying to pair up the "labels" in the `result1` list with the results from your `', '.join([str(item) for item in prog_input])` etc. calls. In that case, please see https://stackoverflow.com/questions/1663807/how-to-iterate-through-two-lists-in-parallel. – Karl Knechtel Nov 29 '21 at 15:36

2 Answers2

1

You were already rather close to solving this, but you have a major error in your approach where you nested the loops over result1 and your text file, when you should have iterated over both simultaneously, e.g. like so:

def c(list1):
    with open("Input progression data.txt") as file:
        for name, data in zip(list1, file):
            print(f'{name}: {data}')
                
c(result1)
mapf
  • 1,906
  • 1
  • 14
  • 40
0

Would this work?

def c(list1):
    x = ""
    y = []
    with open("Input progression data.txt") as file:
        for item in file:
            y.append(item)
    for i in y:
        x = ""
        x += list1[y.index(i)] + ":"
        x += i + '\n'
        print(x)
c(result1)
    
Gamaray
  • 68
  • 1
  • 8