我有一个文件,有多行数据用逗号分隔,如
Mary,F,6919
Anna,F,2698
Emma,F,2034
Elizabeth,F,1852
Margaret,F,1658
Minnie,F,1653
我正在阅读文本文件并尝试拆分单词
filename = 1880.txt
with open(filename) as f:
content = f.readlines()
content = [x.split() for x in content]
它将结果显示为
['Mary,F,9889', 'Anna,F,4283', 'Emma,F,2764', 'Elizabeth,F,2680', 'Minnie,F,2372']
我希望内容变量应返回每行,数据以逗号分隔,如
[('Mary','F','9889'), ('Anna','F','4283'), ('Emma','F','2764'), ('Elizabeth','F','2680'), ('Minnie,'F','2372')]
我使用拆分功能的错误在哪里?
答案 0 :(得分:2)
答案应该是
filename = 1880.txt
with open(filename) as f:
content = f.readlines()
content = [x.strip().split(',') for x in content]
答案 1 :(得分:1)
您可以迭代文件对象一次,应用str.strip
删除尾随'\n'
:
new_data = [tuple(i.strip('\n').split(',')) for i in open('filename.txt')]