从文本文件python中读取和拆分信息

时间:2018-09-24 16:37:35

标签: python

我陷入了一个问题:

我有一个名为id_numbers.txt的文本文件,其中包含以下信息:

325255, Jan Jansen

334343, Erik Materus

235434, Ali Ahson

645345, Eva Versteeg

534545, Jan de Wilde

345355, Henk de Vries

我需要python在逗号处分割信息并编写一个程序来显示信息,如下所示:

Jan Jansen has cardnumber: 325255

Erik Materus has cardnumber: 334343

Ali Ahson  has cardnumber: 235434

Eva Versteeg has cardnumber: 645345

我尝试将其转换为list和split(","),但最终添加了下一个数字,如下所示:

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

我们将不胜感激!

1 个答案:

答案 0 :(得分:4)

您可以这样做

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))