HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Reading data from file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromfilereadingdata

Problem

This reads a list of points from a file with a certain format:


x1 y1
x2 y2


How I can make it better?

from collections import namedtuple
Point = namedtuple('Point ', ['x', 'y'])
def read():
    ins = open("PATH_TO_FILE", "r")
    array = []
    first = True
    expected_length = 0
    for line in ins:
        if first:
            expected_length = int(line.rstrip('\n'))
            first = False
        else:
            parsed = line.rstrip('\n').split ()
            array.append(Point(int(parsed[0]), int(parsed[1])))
    if expected_length != len(array):
        raise NameError("error on read")
    return  array

Solution

Another improvement is to use open as a context manager so that you don't have to remember to .close() the file object even if there are errors while reading.

def read():
    with open("FILE", "r") as f:
        array = []
        expected_length = int(f.next())
        for line in f:
            parsed = map(int, line.split())
            array.append(Point(*parsed))
        if expected_length != len(array):
            raise NameError('error on read')
        return array


See http://docs.python.org/2/library/stdtypes.html#file.close for more details.

Code Snippets

def read():
    with open("FILE", "r") as f:
        array = []
        expected_length = int(f.next())
        for line in f:
            parsed = map(int, line.split())
            array.append(Point(*parsed))
        if expected_length != len(array):
            raise NameError('error on read')
        return array

Context

StackExchange Code Review Q#19588, answer score: 4

Revisions (0)

No revisions yet.