2013-06-27 44 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!它的工作.. :)对不起以前的评论! –

相关问题