【问题标题】:Python ".write"Python“.write”
【发布时间】:2011-05-20 15:33:35
【问题描述】:

我怎样才能“转换”这个:

input=[(0.25  , 'x1'),(0.20 , 'x2'), ............................]

这样我就可以在 test.txt 中只写这个: x1=0.25, x2=0.20, x3= ....................

f = open('test.txt', 'w')

f.write(输入)

f.close()

我知道打印,这项工作还可以:

 print ' '.join("%s=%s" % (y, x) for x,y in input)

但我不能“导入”f.write(...)


编辑:感谢大家,所有工作,我不记得我可以使用:

f.write(' '.join("%s=%s" % (y, x) for x,y in input))

【问题讨论】:

  • 输出的精度重要吗?
  • 我无法单独导入 f.write 值得关闭。
  • 如果有人知道解决这个问题?

标签: python file text-files


【解决方案1】:

有什么问题

f.write(' '.join("%s=%s" % (y, x) for x,y in input))

?

或者

print >>f, ' '.join("%s=%s" % (y, x) for x,y in input)

有一个细微的区别,前者没有尾随换行符。不过很容易修复。

【讨论】:

    【解决方案2】:

    试试这个:

    s = ', '.join("%s=%s" % (y, x) for x,y in input)
    f.write(s)
    

    【讨论】:

      【解决方案3】:

      如果您想使用print,正确的方法取决于您使用的 Python 版本。对于 Python 2:

      print >>f, ' '.join("%s=%s" % (y, x) for x,y in input)
      

      对于 Python 3:

      print(' '.join("%s=%s" % (y, x) for x,y in input), file=f)
      

      【讨论】:

      • 请使用f.write 而不是print...print 的方式不太好,也不那么明显。
      【解决方案4】:

      你有' '.join("%s=%s" % (y, x) for x,y in input),你正在打印它;将其传递给f.write,这是一个完全有效的表达式:

      f = open('text.txt', 'w')
      f.write(' '.join("%s=%s" % (y, x) for x,y in input))
      f.close()
      

      【讨论】:

        【解决方案5】:
        1. 不要命名input,因为这是一个内置函数
        2. 您可以简单地将您的 print 语句替换为 f.write(' '.join("%s=%s" % (y, x) for x, y in myList),它应该可以正常工作

        【讨论】:

          【解决方案6】:
          f = open('test.txt', 'w')
          f.write(' '.join("%s=%s" % (y, x) for x,y in input))
          f.close()
          

          【讨论】:

            猜你喜欢
            • 2018-07-28
            • 1970-01-01
            • 1970-01-01
            • 2012-08-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-07-10
            相关资源
            最近更新 更多