Joshua
Joshua

Reputation: 29

read and split information from text file python

I'm stuck on a problem:

I have a text file called id_numbers.txt that contains this information:

325255, Jan Jansen

334343, Erik Materus

235434, Ali Ahson

645345, Eva Versteeg

534545, Jan de Wilde

345355, Henk de Vries

I need python to split the information at the comma and write a program that will the display the information as follows:

Jan Jansen has cardnumber: 325255

Erik Materus has cardnumber: 334343

Ali Ahson  has cardnumber: 235434

Eva Versteeg has cardnumber: 645345

I've tried to convert to list and split(",") but that ends up adding the next number like this:

['325255', ' Jan Jansen\n334343', ' Erik Materus\n235434', ' Ali Ahson\n645345', ' Eva Versteeg\n534545', ' Jan de Wilde\n345355', ' Henk de Vries']

Help would be appreciated!

Upvotes: 1

Views: 88

Answers (1)

Atul Shanbhag
Atul Shanbhag

Reputation: 636

You can do it this way

with open('id_numbers.txt', 'r') as f:
    for line in f:
        line = line.rstrip() # this removes the \n at the end
        id_num, name = line.split(',')
        name = name.strip() # in case name has trailing spaces in both sides
        print('{0} has cardnumber: {1}'.format(name, id_num))

Upvotes: 4

Related Questions