将文本文件中的数据保存到Python中的数组中
我想读取python中的文本文件。该文件的第一行仅仅是文件的名称,并且该文件的每一行都包含一个实数。我是python的新手,试图解析文件并将数字保存在一个数组中(忽略第一行)。任何帮助将不胜感激。谢谢。将文本文件中的数据保存到Python中的数组中
试试这个,
with open(filename, 'r') as f:
next(f) # discard the first line
l = [int(line) for line in f] # save numbers to a list
阅读第n行,使用itertools.islice
,
import itertools
with open(filename, 'r') as f:
lines_gen = itertools.islice(f, 1, num_lines) # start from 1, read num_lines
l = [int(line) for line in lines_gen]
打开它,跳过第一行,然后将剩下的映射到整数(使用list()
调用将其保存在内存中 - 只有在您打算多次检查或更改它时才需要)。
with open('f.txt') as f:
next(f)
data = list(map(int, f))
这是一个非常pythonic的方式!我建议使用这一个。请注意,下一步的使用是针对python 3.对于python 2,请使用f。 readline() – silviomoreto
@silvio:'next(f)'在Python 2中也能正常工作。 – martineau
你可以这样做:
your_array = []
with open('arrayfile.txt', 'r') as f:
f.readline() # skip first line
for number in f:
your_array.append(int(number))
这似乎工作正常。但是,在501行数据之后,还有另一行是一个字符串。我能否以任何方式创建一个从第2行开始到第500行结束的数组? – Aspro
你并不需要'rstrip()'调用,'int'可以处理尾随空格。 – martineau
@Arya,试试这个,'l = [int(line)for line in f.readlines [2:501]]' – SparkAndShine