0

I want to be able to loop through a list of tuples from my text file and display each tuple.

code:

with open('output.txt', 'r') as f:
    data = f.read()

print(data)

output:

[(21, 21), (21, 90), (90, 90), (90, 21)]

what I want:

(21,21)
(21,90)
(90,90)
(90,21)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
yemi.JUMP
  • 313
  • 2
  • 12

2 Answers2

1

Use ast module to convert your string to a list object.

Ex:

with open('output.txt', 'r') as f:
    data = ast.literal_eval(f.read())

for i in data:
    print(i)
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You are almost there, just loop over data to get the tuples

for tup in data:
    print(tup)  

Chances are that your tuple won't actually of the type 'tuple' but be a string instead,

you can use this function in that case,

def str_to_tup(s):
    tempS = s.split(',')
    return (tempS[0].replace('(',''), tempS[1].replace(')','')

I know this can be done more elegantly, but incase no one else answers :)

static const
  • 953
  • 4
  • 16