2013-04-24 204 views
0

將我的打印輸出寫入文件時出現問題。將打印輸出寫入文件(python)

我的代碼:

list1 = [2,3] 
list2 = [4,5] 
list3 = [6,7] 

for (a, b, c) in zip(list1, list2, list3): 
    print a,b,c 

輸出我得到的是:

>>> 
2 4 6 
3 5 7 
>>> 

,但我有保存此輸出的問題,我想:

fileName = open('name.txt','w') 
for (a, b, c) in zip(list1, list2, list3): 
    fileName.write(a,b,c) 

和各種組合像fileName.write(a + b + c)或(abc),但我不成功...

乾杯!

回答

1

的問題是,write方法需要string,和你給它一個int

嘗試使用formatwith

with open('name.txt','w') as fileName: 
    for t in zip(list1, list2, list3): 
     fileName.write('{} {} {}'.format(*t)) 
+0

謝謝,這似乎工作!我只需要弄清楚如何添加行間的空格,任何提示? – kate88 2013-04-24 12:02:23

+0

瞭解它:fileName.write('{} {} {} \ n'.format(* t),歡呼! – kate88 2013-04-24 12:07:18

0

如何使用格式字符串:

fileName.write("%d %d %d" % (a, b, c)) 
+0

嗨,不幸,我的輸出文件是空白的... – kate88 2013-04-24 11:59:01

0

使用with。可能您的文件句柄未關閉,或正確刷新,因此文件爲空。

list1 = [2,3] 
list2 = [4,5] 
list3 = [6,7] 

with open('name.txt', 'w') as f: 
    for (a, b, c) in zip(list1, list2, list3): 
     f.write(a, b, c) 

您還應該注意,這不會在每次寫入結束時創建新行。有文件的內容是相同的,你打印的內容,你可以使用下面的代碼(選擇一個寫方法):

with open('name.txt', 'w') as f: 
    for (a, b, c) in zip(list1, list2, list3): 
     # using '%s' 
     f.write('%s\n' % ' '.join((a, b, c))) 
     # using ''.format() 
     f.write('{}\n'.format(' '.join((a, b, c)))) 
+0

嗨,不幸的是我在這裏得到一個錯誤: f.write(a,b,c) TypeError :函數只需要1個參數(給出3個) – kate88 2013-04-24 11:55:51

+0

這是因爲我告訴過你不要這樣做,請使用我的答案的第二部分 – 2013-04-24 12:05:48

+0

我也試過第二部分,「f.write('%s \ n'%''.join(a,b,c)) TypeError:join()只需要一個參數(給出3)「 – kate88 2013-04-24 12:16:52

0

可以使用print >> file語法:

with open('name.txt','w') as f: 
    for a, b, c in zip(list1, list2, list3): 
     print >> f, a, b, c