[英]How do I read a text file as a list of lists in python
我有一个像这样分成不同行的大文本文件:
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], ....]
这可能就是你要找的...
with open('file_to_read.csv', 'rU') as f:
l1 = []
for ele in f:
line = ele.split('\n')
l1.append(line)
print(l1)
您可能只能使用numpy
的genfromtxt
方法来执行此操作。
from numpy import genfromtxt
lol = genfromtxt('myFile.csv', delimiter=' ')
在此处查找更多信息。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.