2011-11-27 100 views
0

代碼片段:輸出到文件

def after_equals(s): 
    return s.partition(' = ')[-1] 
for k,s in zip(keyword, score): 
    print after_equals(k) + ',' + after_equals(s) 

的代碼打印的輸出:

NORTH,88466 
GUESS,83965 
DRESSES,79379 
RALPH,74897 
MATERIAL,68168 

我需要輸出到文件中。請諮詢如何寫入文件。

+1

什麼有這個做你的代碼片段? – Cito

回答

1

以寫模式打開一個文件,並寫入一個字符串的文件,然後將其關閉:

f = file('myfile.txt','w') 
f.write(s) 
f.close() 

對於您的情況:

def after_equals(s): 
    return s.partition(' = ')[-1] 
f = file('myfile.txt','w') 
for k,s in zip(keyword, score): 
    f.write('%s,%s\n' % (after_equals(k), after_equals(s))) 
f.close() 
+0

它只打印一行,如果文件並拋出ValueError:在控制檯的關閉文件上的I/O操作 – newcane

+0

也許你在循環內調用f.close()? – idanzalz

+0

你是對的。 – newcane

2
with open(filename, 'w') as out: 
    for k,s in zip(keyword, score): 
     print >> out, after_equals(k) + ',' + after_equals(s) 
     # note: ^^^