如何在Python中将输入文件作为整数读取

时间:2015-03-16 02:57:26

标签: python

当多项式的系数用作输入时,我应该制作一个给出合理根的程序。

如何将输入文件作为整数读取? 这是我用于阅读文件的代码:

def input_file(filename):
    with open(filename, "rt") as file:
        read_data = file.read()
    return read_data 

2 个答案:

答案 0 :(得分:0)

这个问题已详细介绍:

How to read numbers from file in Python?

例如,基本思想是读取每一行并根据需要进行解析

你的例子可能是:

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

如果系数比1-number-1-line更复杂,那么你的解析方法就必须改变;我怀疑你的情况需要什么太复杂的

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

您检索它们的格式并不重要。 重要的是您将它们转换为某种数字,因为输入通常是读一个字符串

答案 1 :(得分:0)

如果你打开使用numpy数组,你可以使用loadtxt()函数。还有一个跳过标题行的选项。您还可以设置导入为整数值的选项。 ' D型'如果记忆能正确地为我服务如果你需要一个列表或其他类型的输出,你应该可以适当地进行类型转换。

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')

有更多信息,请访问: http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html

相关问题