从文本文件中读取多个数字

sla*_*rog 10 python text numbers python-3.x

我是python编程的新手,需要帮助才能做到这一点.

我有一个包含多个数字的文本文件,如下所示:

12 35 21
123 12 15
12 18 89
Run Code Online (Sandbox Code Playgroud)

我需要能够读取每行的各个数字,以便能够在数学公式中使用它们.

mgi*_*son 12

在python中,您从文件中读取一行作为字符串.然后,您可以使用字符串来获取所需的数据:

with open("datafile") as f:
    for line in f:  #Line is a string
        #split the string on whitespace, return a list of numbers 
        # (as strings)
        numbers_str = line.split()
        #convert numbers to floats
        numbers_float = [float(x) for x in numbers_str]  #map(float,numbers_str) works too
Run Code Online (Sandbox Code Playgroud)

我已经完成了一系列步骤,但你经常会看到人们将它们结合起来:

with open('datafile') as f:
    for line in f:
        numbers_float = map(float, line.split())
        #work with numbers_float here
Run Code Online (Sandbox Code Playgroud)

最后,在数学公式中使用它们也很容易.首先,创建一个函数:

def function(x,y,z):
    return x+y+z
Run Code Online (Sandbox Code Playgroud)

现在遍历调用函数的文件:

with open('datafile') as f:
    for line in f:
        numbers_float = map(float, line.split())
        print function(numbers_float[0],numbers_float[1],numbers_float[2])
        #shorthand:  print function(*numbers_float)
Run Code Online (Sandbox Code Playgroud)


Dan*_*sen 6

另一种方法是使用numpy调用的函数loadtxt.

import numpy as np

data = np.loadtxt("datafile")
first_row = data[:,0]
second_row = data[:,1]
Run Code Online (Sandbox Code Playgroud)