简体   繁体   English

用python编写输出文本文件

[英]Writing an output text file in python

Currently i have a list of list containing: 目前我有一个列表列表,其中包含:

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

and I'm trying to write the output in the form of a text file where it is formatted 我正在尝试将输出格式化为文本文件的形式

1      2
5      4
10     9

I tried: 我试过了:

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

but I'm getting the error: 但我得到了错误:

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

would appreciate some help on this. 希望对此有所帮助。

You should change your int values to str and add newline char end of it as below : 您应该将int值更改为str,并在其末尾添加换行符char,如下所示:

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()

output file is : 输出文件是:

1 2
5 4
10 9

You can use a format string instead: 您可以改用格式字符串:

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))

You are getting the error because you are directly printing the list elements, perhaps the write method of the file need the parameter to be the string and you're passing directly the list elements. 因为直接打印列表元素,所以可能会收到错误消息,也许文件的write方法需要将参数作为字符串,然后直接传递列表元素。 Do a thing explicitly convert the items of the list to the string and print. 做一件事明确地将列表中的项目转换为字符串并打印。

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

you can use numpy module to write into text file like below. 您可以使用numpy模块将其写入文本文件,如下所示。

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

Thanks 谢谢

Write it with a formatted string 用格式化的字符串写

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM