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

从文本文件python读取和拆分信息,python,Python,我遇到了一个问题: 我有一个名为id_numbers.txt的文本文件,其中包含以下信息: 325255, Jan Jansen 334343, Erik Materus 235434, Ali Ahson 645345, Eva Versteeg 534545, Jan de Wilde 345355, Henk de Vries 谢谢你的帮助 你可以这样做 with open('id_numbers.txt', 'r') as f: for line in f:

我遇到了一个问题:

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

325255, Jan Jansen 334343, Erik Materus 235434, Ali Ahson 645345, Eva Versteeg 534545, Jan de Wilde 345355, Henk de Vries 谢谢你的帮助

你可以这样做

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))
你可以这样做

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

你能发布你的全部示例代码吗?你能发布你的全部示例代码吗?
lines=f。readlines()
是多余的。只需对f中的行执行
。请记住
name
(列表的第二部分)将在开头有一个额外的空格(原始数据在逗号后有空格)。我将修复名称上的toodo lstrip(),现在是第一行
line.rstrip()
是多余的,因为您正在使用
name.strip()
;)删除前导空格和尾随空格<代码>行=f。readlines()是冗余的。只需对f
中的行执行
。请记住
name
(列表的第二部分)将在开头有一个额外的空格(原始数据在逗号后有空格)。我将修复名称上的toodo lstrip(),现在是第一行
line.rstrip()
是多余的,因为您正在使用
name.strip()
;)删除前导空格和尾随空格
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))