2013-06-27 43 views
0

我有一個包含大量熊貓數據框的大型python程序。在每個過程結束時,我需要將輸出寫入文本文件。所以在整個程序中,文本文件必須用「to_csv」和「write」方法更新。以下是我用來編寫文本文件的一些行。問題是文本文件被程序中最後一個進程的行覆蓋。我想在程序中多次寫入文本文件。使用to_csv多次寫入單個文本文件並編寫方法

out = open('results.txt','a') 

out.write('Message') 
out.write(head.idxmax()) 
df.sort(columns='Requests', ascending=False).to_csv('results', sep=' ') 

如果您需要更多解釋請讓我知道。

回答

2

使用mode參數到.to_csv

In [5]: df = DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], 
       'B': ['one', 'two', 'three', 'one', 'two'], 
       'C': np.random.randn(5)}) 


In [6]: with open('test.txt', 'w') as f: 
    ...:  f.write('Testing\n') 
    ...:  


In [7]: !cat 'test.txt' 
Testing 


In [11]: df.to_csv('test.txt', mode='a') 

In [12]: !cat 'test.txt' 
Testing 
,A,B,C 
0,foo,one,0.42364430570326805 
1,foo,two,1.1992467813307852 
2,foo,three,0.4302171615562164 
3,bar,one,0.6837252733791036 
4,bar,two,0.16800783901724345 
+2

我剛測試它,它工作正常。確保您正在編寫第一個更改。使用上下文管理器。打開('results.txt','a')爲f:f.write('Hello'); df.to_csv('results.txt',mode ='a') – TomAugspurger

+0

非常感謝Tom!它的工作.. :)對不起以前的評論! –

相關問題