Raady
Raady

Reputation: 1726

split function returning unexpected result

I have a file having many lines of data separated by comma like

Mary,F,6919
Anna,F,2698
Emma,F,2034
Elizabeth,F,1852
Margaret,F,1658
Minnie,F,1653

I am reading the text file and trying to split the words

filename = 1880.txt
with open(filename) as f:
    content = f.readlines()
content = [x.split() for x in content]

It gives the result as

['Mary,F,9889', 'Anna,F,4283', 'Emma,F,2764', 'Elizabeth,F,2680', 'Minnie,F,2372']

I expect the content variable should return each line with data split at comma like

[('Mary','F','9889'), ('Anna','F','4283'), ('Emma','F','2764'), ('Elizabeth','F','2680'), ('Minnie,'F','2372')]

where is my mistake using the split function?

Upvotes: 1

Views: 56

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

You can iterate over the file object once, applying str.strip to remove the trailing '\n':

new_data = [tuple(i.strip('\n').split(',')) for i in open('filename.txt')]

Upvotes: 1

Wong Jia Hau
Wong Jia Hau

Reputation: 3069

The answer should be

filename = 1880.txt
with open(filename) as f:
content = f.readlines()
    content = [x.strip().split(',') for x in content]

Upvotes: 2

Related Questions