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
  • 48,339
  • 8
  • 43
  • 63
yemi.JUMP
  • 305
  • 2
  • 11

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
  • 78,594
  • 17
  • 67
  • 103
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 :)

Vaibhav Sharma
  • 891
  • 4
  • 14