如何在python中将文本文件作为列表列表读取

时间:2017-11-15 00:55:38

标签: python list

我有一个像这样的大文本文件分成不同的行:

35 4 23 12 8 \ n 23 6 78 3 5 \ n 27 4 9 10 \ n 73 5 \ n

我需要将它转换为列表列表,每行都是一个单独的元素:

[[35,4,23,12,8],[23,6,78,3,5],[27,4,9,10],[73,5],...... ]

3 个答案:

答案 0 :(得分:1)

这可能是您要寻找的...

with open('file_to_read.csv', 'rU') as f:
        l1 = []
        for ele in f:
            line = ele.split('\n')
            l1.append(line)
print(l1)

答案 1 :(得分:0)

您可能只能使用genfromtxt中的numpy方法来执行此操作。

from numpy import genfromtxt 
lol = genfromtxt('myFile.csv', delimiter=' ')

查找更多信息here

答案 2 :(得分:0)

lines = [line.split() for line in open('yourtextfile.txt')]  # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers.

或者,以下内容也会将您的值转换为int:

lines = [[int(v) for v in line.split()] for line in open('yourtextfile.txt')] # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers that are converted to int()