简体   繁体   English

尝试将元素从文本文件导入列表

[英]Trying to import elements from a text file to a list

I have a text file that contains information about customers for a bus company booking system.我有一个文本文件,其中包含有关巴士公司预订系统的客户信息。 The file is laid out as such:该文件的布局如下:

id, name, customer discount, total money spent

Eg part of the file is:例如文件的一部分是:

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

I want to import this information to a list in Python, but I only need the ids and names.我想将这些信息导入到Python中的一个列表中,但我只需要ids和names。 I've tried a few different ways of importing the information, but I can only import the whole file to a list and even then it always comes out like this:我尝试了几种不同的导入信息的方法,但我只能将整个文件导入到一个列表中,即使那样它总是这样出现:

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

And I don't even know how to begin separating the items so that I can just have the id and name in the list.而且我什至不知道如何开始分离项目,以便我可以在列表中只包含 ID 和名称。

Since your text file contains comma-separated values, the csv module likely will be most useful.由于您的文本文件包含逗号分隔值,因此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

The useful part of the csv module reading the file as a dictionary assigns the column names to each row's field, making it easy to index which column names you want to select, such as row['id'] and row['name'] . csv 模块有用的部分将文件作为字典读取文件,将列名分配给每一行的字段,从而可以轻松索引您想要的列名 select,例如row['id']row['name'] .

Also, since you mentioned you want to "just have the id and name in the list", at first create an empty list, then append each rows items to that list as so:此外,由于您提到您想要“在列表中只包含 id 和名称”,首先创建一个空列表,然后 append 每个行项目到该列表,如下所示:

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']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM