Arya Arya - 8 months ago 21
Python Question

Save data from a text file into an array in Python

I am trying to read a text file in python. The first line of the file is just the name of the file and rest each line of the file contains a real number. I am new to python and trying to parse the file and save the numbers in a single array (ignoring the first line). Any help would be highly appreciated. Thank you.


Try this,

with open(filename, 'r') as f:
    next(f) # discard the first line
    l = [int(line) for line in f]   # save numbers to a list

Read the first n lines, use 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]