1

我正在尝试逐行读取每一行并将每一行转换为元组,如以下考试所示:

可能的重复: 将字符串转换为元组

input_1.txt

126871 test
126262 value test

结果.txt

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

示例代码:

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

非常感谢您的任何建议。

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 回答