2010-02-22 71 views
0

我的Python模塊有一個列表,其中包含我想要保存爲某個.txt文件的所有數據。該列表包含多個元組,像這樣:導出列表爲.txt(Python)

list = [ ('one', 'two', 'three'), ('four', 'five', 'six')] 

如何打印列表,以便每個元組項目是由製表符分隔,並且每個元組由一個換行符分開?

感謝

回答

8
print '\n'.join('\t'.join(x) for x in L) 
+0

說'序列項目0:期望的字符串,找到的元組' – 3zzy 2010-02-22 04:58:19

+0

是。修正了。 – 2010-02-22 04:58:55

2

試試這個

"\n".join(map("\t".join,l)) 

測試

>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')] 
>>> print "\n".join(map("\t".join,l)) 
one  two  three 
four five six 
>>> 
+0

'map'構建列表 - 不必要的。 – 2010-03-19 23:30:00

2
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list)) 
+0

說'參數1必須是字符串或只讀字符緩衝區,而不是發生器' – 3zzy 2010-02-22 04:59:11

+0

我糾正它,再試一次 – 2010-02-22 05:39:41

1

最習慣的方法,恕我直言,是用一個列表理解和聯接:

print '\n'.join('\t'.join(i) for i in l) 
+0

我看到這裏沒有列表理解。 – 2010-03-19 23:29:11

9

你可以解決它,因爲其他答案只是通過加入行來提示,但更好的方法是隻使用python csv模塊,以便稍後可以輕鬆更改分隔符或添加標頭等並將其讀回,看起來像你想製表符分隔的文件

import sys 
import csv 

csv_writer = csv.writer(sys.stdout, delimiter='\t') 
rows = [ ('one', 'two', 'three'), ('four', 'five', 'six')] 
csv_writer.writerows(rows) 

輸出:

one two three 
four five six 
+0

感謝您的替代方法,但我太初學者嘗試它:) – 3zzy 2010-02-22 05:09:40

+0

但方式,它更簡單,因爲你只是使用std庫,但是對於初學者,你也必須知道如何去做:) – 2010-02-22 05:13:53

+1

好的解決方案不過,不要使用'list'作爲變量名稱。 – 2010-02-22 06:50:34

0

您不必參加提前名單:

with open("output.txt", "w") as fp: 
    fp.writelines('%s\n' % '\t'.join(items) for items in a_list)