【问题标题】:How to read in floats from a file?如何从文件中读取浮点数?
【发布时间】:2012-06-15 15:05:40
【问题描述】:

如何在 Python 中打开文件并从文件中读取浮点数,当它是字符串格式时?我还想更改每个浮点数的值并用新值重写文件。

【问题讨论】:

  • 您在哪一部分遇到了问题?

标签: python string file floating-point


【解决方案1】:

假设每行有一个浮点数:

with open("myfile") as f:
    floats = map(float, f)

# change floats

with open("myfile", "w") as f:
    f.write("\n".join(map(str, floats)))

如果您想对格式进行更多控制,请使用字符串的format method。例如,这只会在每个句点后打印 3 位数字:

    f.write("\n".join(map("{0:.3f}".format, floats)))

【讨论】:

    【解决方案2】:

    “float()”函数接受字符串作为输入并将它们转换为浮点数。

    >>> float("123.456")
    123.456
    

    【讨论】:

      【解决方案3】:
      def get_numbers():
          with open("yourfile.txt") as input_file:
              for line in input_file:
                  line = line.strip()
                  for number in line.split():
                      yield float(number)
      

      完成后再写回来

      作为一个较短的版本(未经测试,从头开始编写)

      with open("yourfile.txt") as input_file:
          numbers = (float(number) for number in (line for line in (line.split() for line in input_file)))
      

      【讨论】:

        【解决方案4】:

        如果你想读取 input_num 浮点数:

        import numpy as np
        import struct
        float_size=4
        np.array(struct.unpack('<'+str(input_num)+'f',
                            fin.read(float_size*input_num)))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多