首页 文章

如何使用Python将文本文件读入列表或数组

提问于
浏览
87

我试图在python中读取文本文件的行到列表或数组 . 我只需要能够在创建后单独访问列表或数组中的任何项目 .

文本文件的格式如下:

0,0,200,0,53,1,0,255,...,0.

... 在上面的位置,实际的文本文件有数百或数千个项目 .

我正在使用以下代码尝试将文件读入列表:

text_file = open("filename.dat", "r")
lines = text_file.readlines()
print lines
print len(lines)
text_file.close()

我得到的输出是:

['0,0,200,0,53,1,0,255,...,0.']
1

显然,它将整个文件读入只有一个项目的列表,而不是单个项目的列表 . 我究竟做错了什么?

6 回答

  • 76
    with open('D:\python\positive.txt', 'r') as myfile: data=myfile.read().replace('\n', '')
    
  • 3

    您必须使用 split() 将字符串拆分为值列表

    所以,

    lines = text_file.read().split(',')
    
  • 33

    你也可以使用numpy loadtxt

    from numpy import loadtxt
    lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)
    
  • 93

    所以你想创建一个列表列表......我们需要从一个空列表开始

    list_of_lists = []
    

    接下来,我们逐行阅读文件内容

    with open('data') as f:
        for line in f:
            inner_list = [elt.strip() for elt in line.split(',')]
            # in alternative, if you need to use the file content as numbers
            # inner_list = [int(elt.strip()) for elt in line.split(',')]
            list_of_lists.append(inner_list)
    

    一个常见的用例是柱状数据,但我们的存储单元是文件的行,我们已逐一阅读,因此您可能想要转置列表列表 . 这可以通过以下习语来完成

    by_cols = zip(*list_of_lists)
    

    另一个常见用途是为每列提供一个名称

    col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
    by_names = {}
    for i, col_name in enumerate(col_names):
        by_names[col_name] = by_cols[i]
    

    这样您就可以对同类数据项进行操作

    mean_apple_prices = [money/fruits for money, fruits in
                         zip(by_names['apples revenue'], by_names['apples_sold'])]
    

    我写的大部分内容都可以使用标准库中的 csv 模块加速 . 另一个第三方模块是 pandas ,它允许您自动化典型数据分析的大多数方面(但具有许多依赖性) .


    更新在Python 2中 zip(*list_of_lists) 返回一个不同的(转置的)列表列表,在Python 3中情况发生了变化, zip(*list_of_lists) 返回了一个不可订阅的zip对象 .

    如果您需要索引访问,则可以使用

    by_cols = list(zip(*list_of_lists))
    

    它为您提供了两个版本的Python列表 .

    另一方面,如果你不需要索引访问,你想要的只是 Build 一个由列名索引的字典,一个zip对象就好了......

    file = open('some_data.csv')
    names = get_names(next(file))
    columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
    d = {}
    for name, column in zip(names, columns): d[name] = column
    
  • 14

    This question is asking how to read the comma-separated value contents from a file into an iterable list:

    0,0,200,0,53,1,0,255,...,0.

    The easiest way to do this is with the csv module as follows:

    import csv
    with open('filename.dat', newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
    

    Now, you can easily iterate over spamreader like this:

    for row in spamreader:
        print(', '.join(row))
    

    See documentation for more examples.

  • 0

    python's file.readLines() method returns a list of the lines in the file:

    f = open('file_name.ext', 'r')
    x = f.readlines()
    f.close()
    

    现在你应该能够遍历x行数组 .

    如果您想使用该文件而不必记得以后关闭它,请执行以下操作:

    with open('file_name.ext', 'r') as f:
        x = f.readlines()
    

相关问题