【问题标题】:Can't output Float values to text file using Python 3无法使用 Python 3 将浮点值输出到文本文件
【发布时间】:2014-09-22 13:54:16
【问题描述】:

我的代码当前生成一个仅包含浮点值的数组 (ra)。如果此数组中的值满足某个条件,我想将该特定值输出到文本文件。这是我有问题的代码部分:

outputFile = open('outFile.txt', 'wb')
i = 0
membersOuter = []
membersInner = []
membersCore = []
while i < (len(ra)):
    DiffFinal = Diff[i] * 3600 * kpc_per_arcsec / 1000 #just converting values from an array called Diff
    if DiffFinal < 2.0:
        membersOuter.append(ra[i])
    if DiffFinal < 1.0:
        membersInner.append(ra[i])
    if DiffFinal < 0.5:
        membersCore.append(ra[i])
        outputFile.write(ra[i] + ' ') #this is the part causing problems
    i += 1

代码成功地为 3 个成员类别创建了数组。但是,我希望能够将满足最终条件的 ra 值(都是浮点数)输出到 outFile.txt。当我运行此代码时,我收到错误:

TypeError: 'float' does not support the buffer interface

我使用的是 Python 3.4,并且搜索过去的问题告诉我,这个过程自较低版本以来发生了变化。建议的一些更改包括:

outputFile.write(str(ra[i]))
TypeError: 'str' does not support the buffer interface

outputFile.write(bytes(ra[i]))
TypeError: 'float' object is not iterable

【问题讨论】:

  • str(ra[i]).encode('ascii')bytes(str(ra[i]),'ascii')?
  • 就是这样 - 谢谢 vaultah!
  • 有没有比输入outputFile.write(str(ra[i]).encode('ascii') + ' \n'.encode('ascii'))更简单的方法来包含空格/换行符
  • 如果是文本文件,为什么要用wb打开?
  • 是的,如果将来有人正在阅读本文,请使用“w”,而不是“wb”。虽然 vaultah 的建议确实有效,但如果你使用 'wb'

标签: python python-3.x floating-point output


【解决方案1】:

字符串格式应该可以帮助您解决这两个问题。这是您的示例,删除了一些不相关的部分:

ra = [1.5, 2.1, 3.3, 11./7]

outputFile = open('outFile.txt', 'w')
for i in range(4):
    outputFile.write('{} \n'.format(ra[i]))

注意:

  • 输出文本文件是为文本打开的,不是二进制的,w,不是wb
  • float 变量由字符串中的{} 指令格式化。
  • 空格和换行符很容易包含在格式字符串中。

【讨论】:

  • 在您发表评论并查看模式图表后切换到“w” - 刚刚在网上看到了一个使用“wb”的示例(此处为初学者)。我还可以通过将outputFile.write('{} \n'.format(y[i])) 放在第一个 outputFile.write 命令下方(将 \n 从 ra 中取出)来在单独的列中添加另一个数组。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多