cress - 4 years ago 115
Python Question

# Read set of tuple numbers from a file

I have a file with the first two lines looking like this:

``````(1,233)(44,444)(2323,545)(0,0)(22,2)(5,0)(222,2)(0,5)(12,2)(22,3)
(0,223)(44,424)(123,545)(0,1)(42,2)(5,0)(52,2)(0,6)(17,4)(3,3)
``````

I want to read each tuple and get each number (without the commas and parenthesis). I read like this:

``````file = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
if file is None:
return False

with open(file, 'r') as f:
firstLine = lines[0]
secondLine = lines[1]

# Run loop here to get the tuple values
# firstNum = tuple[0]
# secondNum = tuple[1]

# Go to next line and do the same
``````

How can I go about doing the above? Any help would be appreciated.

## First way

Replace all brackets and commas with spaces and then split the line removing the spaces. Thus, you obtain a flat list of all the numbers. By iterating through the list and getting the numbers at indices `i` and `i+1`, you can get them in pairs.

``````>>> line = "(1,233)(44,444)(2323,545)(0,0)(22,2)(5,0)(222,2)(0,5)(12,2)(22,3)"
>>> line_edited = line.replace("(", " ").replace(")", " ").replace(",", " ").split()
>>> line_edited
['1', '233', '44', '444', '2323', '545', '0', '0', '22', '2', '5', '0', '222', '2', '0', '5', '12', '2', '22', '3']
>>> for i in xrange(0, len(line_edited), 2):
print line_edited[i], line_edited[i+1]

1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3
``````

## Second way

Similar to the first way, except that you only replace the brackets with spaces and split. Now, you get a list of strings `"first_number,second_number"`, so you iterate through those and split at the comma to get the pair.

``````>>> line_edited = line.replace("(", " ").replace(")", " ").split()
>>> line_edited
['1,233', '44,444', '2323,545', '0,0', '22,2', '5,0', '222,2', '0,5', '12,2', '22,3']
>>> for pair in line_edited:
first_number, second_number = pair.split(",")
print first_number, second_number

1 233
44 444
2323 545
0 0
22 2
5 0
222 2
0 5
12 2
22 3
``````

You can read more about replacing multiple characters in a string here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download