Arya Arya - 1 year ago 214
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.

Answer Source

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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download