【问题标题】:save a txt file in Python, some tips to improve my code [closed]在 Python 中保存一个 txt 文件,一些改进我的代码的技巧 [关闭]
【发布时间】:2012-11-30 16:34:48
【问题描述】:

首先,很抱歉这个简单的问题。我知道这些问题非常基础。我需要在 Python 2.7 中保存一个包含多行的 txt 文件。我需要提出一些建议来改进我的基本代码。

这是一个基本的例子

file_out = open("..//example//test.text", "w")

for p in range(10):
    ID = str(p)
    A = p*10
    B = p+10
    C = p-10
    D = p+p
    E = p*2
    file_out.write("s% %s %s %s s% s%" % (ID,A,B,C,D,E)+ "\n")
file_out.close()

我的问题是:

  • 我收到此错误消息,但我没有找到解决方法

    Traceback (most recent call last):
    File "<interactive input>", line 1, in <module>
      ValueError: incomplete format
    
  • 我要保存的元素(例如:ID、A、B、C、D、E)有几个(30 个元素),并且 我用了很长的 s%。是否有一种优雅且紧凑的编码方式 这条线?。

  • 我还想保存一个头像(例如:ID、A、B、C、D、E)。什么是最好的方法 这样做?

【问题讨论】:

    标签: python performance coding-style


    【解决方案1】:

    ValueError: 格式不完整

    您将一半的%s 格式写为s%。百分号在前。

    我要保存的元素(例如:ID、A、B、C、D、E)有几个(30 个元素),我使用了一长串 s%。是否有一种优雅且紧凑的方式来编写这一行代码?

    ' '.join(str(x) for x in [p, p*10, p+10, p-10, p+p, p*2])
    

    【讨论】:

    • @johan 谢谢。要保存一个标题,我需要在 ' '.join(str(x) for x in [p, p*10, p+10, p-10, p+p, p*2])?
    【解决方案2】:

    你有错别字

    file_out.write("%s %s %s %s %s %s" % (ID,A,B,C,D,E)+ "\n")
    

       file_out.write("%s %s %s %s %s %s\n" % (ID,A,B,C,D,E))
    

    file_out.write(" ".join(["%s" %i for i in [A, B, C, D, E]]))
    

    【讨论】:

    • 谢谢。我不明白如何创建标题(我的 txt 文件的第一行(
    【解决方案3】:

    % 首先,然后是说明符。

    %s
    

    还有:

    print >>file_out, ' '.join(...)
    

    另外,csv

    【讨论】:

      【解决方案4】:

      您有一些语法错误。检查您的格式字符串。

      file_out = open("..//example//test.text", "w")
      
      for p in range(10):
          ID = str(p)
          A = p*10
          B = p+10
          C = p-10
          D = p+p
          E = p*2
          file_out.write("%s %s %s %s %s %s" % (ID,A,B,C,D,E) + "\n")
      file_out.close()
      

      【讨论】:

        猜你喜欢
        • 2011-07-12
        • 1970-01-01
        • 1970-01-01
        • 2020-03-26
        • 2022-08-18
        • 2014-01-02
        • 1970-01-01
        • 2019-01-09
        相关资源
        最近更新 更多