-1

I'm supposed to be making a program that gives rational roots when the coefficients of a polynomial are used as the input.

How do I read the input file as integers? This is the code i'm using for the reading of the file:

def input_file(filename):
    with open(filename, "rt") as file:
        read_data = file.read()
    return read_data 
connie
  • 29
  • 1
  • 7

2 Answers2

0

This question has been covered at length:

How to read numbers from file in Python?

e.g., the basic idea is to read each line and parse it as need be

Your example might be:

def input_file(filename):
    coefficients = []
    with open(filename,'rt') as file:
        for line in file: # loop over each line
            coefficients.append(float(line)) # parse them in some way
    return coefficients

If the coefficients we more complicated than 1-number-1-line, your parsing method would have to change; I doubt your circumstances require anything too complicated

...
for line in file:
    # say the numbers are separated by an underscore on each line
    coefficients.append([float(coef) for coef in line.split('_')])

It doesn't really matter what format you retrieve them in. What is important is that you cast them to some kind of number, since input is typically read a a string

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46
  • what if the numbers in my input file had commas? like 0,-2,1,15? – connie Mar 16 '15 at 03:24
  • take a look at the second code-example. Read in a line, split it using the split method by whatever delineator (in my example I used underscores, you would want commas) you want, then cast it to a number and add it to the list. The method returns a list of numbers which would be your coefficients; you can return whatever format you want – en_Knight Mar 16 '15 at 03:26
0

if you are open to using a numpy array, you could use the loadtxt() function. there is also an option for skipping lines for headers. you can also set an option to import as integer values. 'dtype' if memory serves me correctly. if you needed a list or other type of output, you should be able to typecast appropriatly.

import numpy as np
def input_file(filename):
    with open(filename, "rt") as file:
        arr = np.loadtxt(file)
    return arr 

r = input_file('test.txt')

more information is available at http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

m25
  • 1,473
  • 2
  • 13
  • 14