【问题标题】:Trying to import elements from a text file to a list尝试将元素从文本文件导入列表
【发布时间】:2021-10-03 07:59:27
【问题描述】:

我有一个文本文件,其中包含巴士公司预订系统的客户信息。 该文件的布局如下:

id, name, customer discount, total money spent

例如文件的一部分是:

C1, James, 0, 100
C2, Lily, 0, 30

我想将此信息导入 Python 中的列表,但我只需要 id 和名称。 我尝试了几种不同的方式来导入信息,但我只能将整个文件导入到一个列表中,即使这样,它也总是这样:

[['C1,' 'James,' '0', '100'], ['C2', 'Lily', '0', '30']]

而且我什至不知道如何开始分隔项目,以便我可以在列表中只包含 id 和 name。

【问题讨论】:

  • 看看 csv 和/或 pandas 模块
  • 到目前为止你尝试了什么?请分享代码。

标签: python csv


【解决方案1】:

由于您的文本文件包含逗号分隔值,csv 模块可能最有用。

import csv

with open ('data.txt', 'r') as fh:
    header = [h.strip() for h in next(fh).split(',')] # remove spaces and assign the header to dictionary keys
    reader = csv.DictReader(fh, fieldnames=header) # read the row contents assigning names to the fields
    for row in reader:
        print(row['id'], row['name'])

C1  James
C2  Lily

将文件作为字典读取的 csv 模块的有用部分将列名分配给每一行的字段,从而可以轻松索引您要选择的列名,例如 row['id']row['name']

此外,由于您提到您希望“只在列表中包含 id 和名称”,首先创建一个空列表,然后将每行项目附加到该列表中:

import csv

id_name = [] # list to store ids, names

with open ('data.txt', 'r') as fh:
    header = [h.strip() for h in next(fh).split(',')]
    reader = csv.DictReader(fh, fieldnames=header)
    for row in reader:
        # print(row['id'], row['name'])
        id_name.append([row['id'], row['name']])

print(id_name) # print the resulting list

[['C1', ' James'], ['C2', ' Lily']]

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2020-07-16
    相关资源
    最近更新 更多