簡體   English   中英

用python編寫輸出文本文件

[英]Writing an output text file in python

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

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

希望對此有所幫助。

您應該將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()

輸出文件是:

1 2
5 4
10 9

您可以改用格式字符串:

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

因為直接打印列表元素,所以可能會收到錯誤消息,也許文件的write方法需要將參數作為字符串,然后直接傳遞列表元素。 做一件事明確地將列表中的項目轉換為字符串並打印。

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

您可以使用numpy模塊將其寫入文本文件,如下所示。

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

謝謝

用格式化的字符串寫

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