2014-09-02 64 views
0

如何將以下代碼的結果導出到python的csv文件中?如何將打印結果導出到Python中的csv文件中?

print(['%s %0.2f'%(node,centrality[node]) for node in centrality]) 

結果看起來是這樣的:

['faef 0.37', 'efef 0.60', 'vsav 0.60', 'fadf 0.37'] 

而且我希望它是這樣一個FILE.CSV:

faef,0.37 
efef,0.60 
vsav,0.60 
fadf,0.37 

THX領先!我使用Python 2.7在Ubuntu

回答

0
import csv  
data = ['faef 0.37', 'efef 0.60', 'vsav 0.60', 'fadf 0.37'] 

with open('file.csv', 'w', newline='') as fp: 
    a = csv.writer(fp, delimiter=',') 
    complete_data = [] 
    for d in data: 
     data_to_write = d.split(" ") 
     complete_data.append(data_to_write) 
    a.writerows(data) 
0
import csv 

result = ['faef 0.37', 'efef 0.60', 'vsav 0.60', 'fadf 0.37']  
with open('path/to/file', 'w') as outfilehandle: 
    outfile = csv.writer(outfilehandle, delimiter=',') 
    outfile.writelines([s.split() for s in result]) 
0
import csv 

data = ['faef 0.37', 'efef 0.60', 'vsav 0.60', 'fadf 0.37'] 
with open('test.csv', 'w') as fp: 
    writer = csv.writer(fp, delimiter=',') 
    for x in data: 
     k, v = x.split(' ') 
     writer.writerow([k, v]) 

輸出文件

faef,0.37 
efef,0.60 
vsav,0.60 
fadf,0.37 
相關問題