-1
set1 = [(1,21,0),(1,20,0),(1,19,0),(1,18,0),(1,17,0)]
set2 = [(2,21,0),(2,20,0),(2,19,0),(2,18,0),(2,17,0),(2,16,0),(2,15,0)]

setNumber = [1,2]

for num in setNumber:
    
    test = 'set'+str(num)

    for (a,b,c) in test:

        with open('test'+str(num)+'.csv','a') as f:
            writer = csv.writer(f)
            row_data = [a,b,c]
            writer.writerow(row_data)
            f.close

I have two list of tuples of numbers and I want to create a loop that can go through each list but I can't make 'test' as a "range variable".

if test = set1 or test = set2, no issue, files are created.

Thanks for the help.

David Y
  • 3
  • 1
  • `test` is not the _variable `set1` or `set2`_, it is the _string_ `"set1"` or `"set2"`. Your line `for a, b, c in test` fails just like `for a, b, c in "set1"` would. – Pranav Hosangadi Dec 14 '22 at 04:10
  • Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Pranav Hosangadi Dec 14 '22 at 04:11
  • Also open your file _once_ before the `for num in setNumber` loop, do everything you want with it, and finally let it close automatically upon exiting the `with`. There is no need to call` f.close()` (you probably have a typo in `f.close`, which is a pointless statement) – Pranav Hosangadi Dec 14 '22 at 04:12

1 Answers1

0

You can put yout two sets (set1 and set2) in a list, and use a for loop to have your test variable go through the different sets.

set1 = [(1,21,0),(1,20,0),(1,19,0),(1,18,0),(1,17,0)]
set2 = [(2,21,0),(2,20,0),(2,19,0),(2,18,0),(2,17,0),(2,16,0),(2,15,0)]
sets = [set1, set2]

for i, test in enumerate(sets):
    
  for (a,b,c) in test:

    with open('test'+str(i)+'.csv','a') as f:
        writer = csv.writer(f)
        row_data = [a,b,c]
        writer.writerow(row_data)
        f.close
1001pepi
  • 114
  • 4