【问题标题】:Reading multiple numbers from a text file从文本文件中读取多个数字
【发布时间】:2012-10-06 17:21:47
【问题描述】:

我是 python 编程新手,需要帮助。

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

12 35 21
123 12 15
12 18 89

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

【问题讨论】:

  • [map(float, ln.split()) for ln in open("filename") if ln.strip()]

标签: python text python-3.x numbers


【解决方案1】:

如果您想在命令行中使用文件名作为参数,则可以执行以下操作:

    from sys import argv

    input_file = argv[1]
    with open(input_file,"r") as input_data:
        A= [map(int,num.split()) for num in input_data.readlines()]

    print A #read out your imported data

否则你可以这样做:

    from os.path import dirname

    with open(dirname(__file__) + '/filename.txt') as input_data:
        A= [map(int,num.split()) for num in input_data.readlines()]

    print A

【讨论】:

    【解决方案2】:

    如果您将文件命名为 numbers.txt,这应该可以工作

    def get_numbers_from_file(file_name):
        file = open(file_name, "r")
        strnumbers = file.read().split()
        return map(int, strnumbers)
    
    
    print get_numbers_from_file("numbers.txt")
    

    这必须返回 [12, 35, 21, 123, 12, 15, 12, 18, 89] 在您可以使用 list_variable[intergrer] 单独选择每个数字之后

    【讨论】:

      【解决方案3】:

      下面的代码应该可以工作

      f = open('somefile.txt','r')
      arrayList = []
      for line in f.readlines():
          arrayList.extend(line.split())
      f.close()
      

      【讨论】:

        【解决方案4】:

        在 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
        

        我已经通过一系列步骤完成了这一切,但您经常会看到人们将它们组合在一起:

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

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

        def function(x,y,z):
            return x+y+z
        

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

        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)
        

        【讨论】:

          【解决方案5】:

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

          import numpy as np
          
          data = np.loadtxt("datafile")
          first_row = data[:,0]
          second_row = data[:,1]
          

          【讨论】:

            猜你喜欢
            • 2013-03-10
            • 2015-08-11
            • 2014-04-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-11-08
            • 2010-12-13
            • 2021-12-19
            相关资源
            最近更新 更多