【问题标题】:Writing an output text file in python在 python 中编写输出文本文件
【发布时间】:2018-09-21 14:05:08
【问题描述】:

目前我有一个列表,其中包含:

lst = [[1,2],[5,4],[10,9]]

我正在尝试以格式化的文本文件的形式编写输出

1      2
5      4
10     9

我试过了:

newfile = open("output_file.txt","w")
for i in range(len(lst)):
    newfile.write(i)
newfile.close()

但我收到了错误:

TypeError: write() argument must be str, not list

不胜感激。

【问题讨论】:

  • newfile.write(str(i))
  • 你的 i 只是一个索引。您需要执行 lst[i] 或在 lst 上运行循环(如 for l in lst)

标签: python


【解决方案1】:

您应该将 int 值更改为 str 并在其末尾添加换行符,如下所示:

lst = [[1,2],[5,4],[10,9]]

newfile = open("output_file.txt","w")
for i in lst:
    newfile.write(str(i[0]) + ' ' + str(i[1]) + '\n')
newfile.close()

输出文件是:

1 2
5 4
10 9

【讨论】:

    【解决方案2】:

    您可以改用格式字符串:

    lst = [[1,2],[5,4],[10,9]]
    with open("output_file.txt","w") as newfile:
        for i in lst:
            newfile.write('{:<7}{}\n'.format(*i))
    

    【讨论】:

      【解决方案3】:

      您可以使用 numpy 模块写入文本文件,如下所示。

      import numpy as np
      lst = [[1,2],[5,4],[10,9]]
      np.savetxt('output_file.txt',lst,fmt='%d')
      

      谢谢

      【讨论】:

        【解决方案4】:

        用格式化的字符串写出来

        with open('output.txt', 'w') as f:
            for i in lst:
                f.write('{}\t{}\n'.format(i[0], i[1]))
        
        (xenial)vash@localhost:~/python/stack_overflow/sept$ cat output.txt
        1     2
        5     4
        10    9
        

        【讨论】:

          【解决方案5】:

          您收到错误是因为您直接打印列表元素,也许文件的 write 方法需要参数为字符串,而您直接传递列表元素。 做一件事将列表中的项目显式转换为字符串并打印。

           newfile = open("output_file.txt","w")
           for i in range(len(lst)):
              newfile.write(str(i))
           newfile.close()
          

          【讨论】:

            猜你喜欢
            • 2022-08-09
            • 2017-07-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-02-08
            相关资源
            最近更新 更多