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.

4

1 に答える 1

2

使用str.split:

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

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

これらのタプルをファイルに書き込みたい場合は、最初に次を使用して文字列に変換します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')
于 2013-07-08T00:31:30.970 に答える