1

I'm trying to read each line by line and convert each line to tuple as showing in the following exam:

Possible Duplicata: Converting String to Tuple

input_1.txt

126871 test
126262 value test

result.txt

('126871', 'test')
('126262', 'value', 'test')

Sample Code:

    def string_to_tuple_example():
        with open('Input_file_1.txt', 'r') as myfile1:
            tuples1 = myfile2.readlines()
            print tuples1 #return string, here I STUCK 

Thanks a lot for any suggestion.

Community
  • 1
  • 1

1 Answers1

2

Use str.split:

with open('Input_file_1.txt') as f:
    for line in f:
        print tuple(line.split())

('126871', 'test')
('126262', 'value', 'test')

If you want to write these tuples to a file then convert them to a string first using str:

with open('Input_file_1.txt') as f, open('result.txt','w') as f1 :
    for line in f:
        f1.write(str(tuple(line.split())) + '\n')

>>> !cat result.txt
('126871', 'test')
('126262', 'value', 'test')
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Actually I got the same result but want output as a first bracket as result.txt. Thanks. –  Jul 08 '13 at 00:33
  • @user2412714 I've already mentioned that in my answer, use `tuple(line.split())` if you want a tuple. :) – Ashwini Chaudhary Jul 08 '13 at 00:34
  • @user2412714 see my updated answer, may be that's what you wanted. – Ashwini Chaudhary Jul 08 '13 at 00:39
  • Yes, Thanks @Ashwini Chaudhary If I use line.split() then result will be with the third bracket but if I use tuple(line.split()) then the result will be with the first bracket. –  Jul 08 '13 at 00:45
  • @user2412714 I am not sure what do you mean by third bracket, `str.split` returns a list(`[...]`), if you want parenthesis(`(...)`) then use `tuple()`. – Ashwini Chaudhary Jul 08 '13 at 00:50