用逗号分隔每个单词,然后将整行存储在列表中

时间:2016-05-09 06:34:58

标签: python

我想要读取每行有4个值的文件: 标题,作者,流派,价格。

我想拆分每个带有','作为分隔符的值。然后我想将它保存到我的列表中,每一行都是列表中的一个条目。例如

title, author, genre, price

title2, author2, genre2, price2

这将保存为

List[0][1] = title 
List[0][2] = author 
List[0][3] = genre 
List[0][4] = price

List[1][1] = title2
List[1][2] = author2 
List[1][3] = genre2 
List[1][4] = price2

这是我到目前为止所做的:

def readFile(fileName):
List = []
f = open(fileName, 'r')
line = f.readline()
x = 0
while len(line) != 0:
    for i in range(4):
        List[x][i] = line.split(',')
    x += 1
    line = f.readline()
f.close()
return List

但我刚收到List index out of range

3 个答案:

答案 0 :(得分:2)

这里介绍了Python,只需使用csv module

import csv

def readFile(filename):
    with open(filename, 'rb') as f:
        reader = csv.reader(f)
        return list(reader)

您的代码会产生一些经典错误:

  • str.split()返回一个列表;您试图将该列表分配4次到另一个列表的索引。只需直接使用str.split()返回的列表。
  • 考虑到文件中的行包含行分隔符(\n);你可能想先把它剥掉。
  • 您开始使用列表。您无法分配不存在的索引,而是使用list.append()来添加元素。
  • 您无需测试len(line) != 0;只有if line:就足够了,因为空字符串在真值测试中被认为是'假的'。见Truth Value Testing
  • 您不需要每次都使用file.readline();只需使用for line in f:循环,您将逐个获取每一行,因为文件对象可迭代
  • 如果您使用file as a context manager(使用with语句),Python将为您关闭该文件。

因此,如果没有csv模块,您可以像这样编写代码:

def readFile(fileName):
    rows = []
    with open(fileName, 'r') as f:
        for line in f:
            columns = line.strip().split(',')
            rows.append(columns)
    return rows

答案 1 :(得分:0)

我认为您可以使用Python List Comprehensions,以更少的代码实现您的功能。

export class Student {
  id: number;
  name: string;
  age:number;
}

上述程序相当于以下程序:

getStudents (): Observable< Student[]> 

答案 2 :(得分:-1)

   with open(filname,'r') as f:
        lst_data = f.readlines()

    List = []
    for data in lst_data:
        List.append(data.strip().split(','))

列表将包含这样的数据

List[0][1] = title 
List[0][2] = author 
List[0][3] = genre 
List[0][4] = price

List[1][1] = title2
List[1][2] = author2 
List[1][3] = genre2 
List[1][4] = price2
相关问题