我正在尝试逐行阅读并将每行转换为元组,如以下考试所示:
可能的Duplicata:Converting String to Tuple
input_1.txt
126871 test
126262 value test
的Result.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
非常感谢任何建议。
答案 0 :(得分: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')