打印python输出到文件不起作用

时间:2013-06-07 17:49:00

标签: python

我有以下功能

outFile = open("svm_light/{0}/predictions-average.txt".format(hashtag), "a")
with open('svm_light/{0}/predictions-{1}'.format(hashtag,segMent)) as f:
    tot_sum = 0
    for i,x in enumerate(f, 1):
        val = float(x)
        tot_sum += val            
        average = tot_sum/i
        outFile.write(average)  

我只是尝试将每个平均值的输出打印到每行1个平均值。 但是我得到以下错误...

  outFile.write(average)            
TypeError: expected a character buffer object

如果我只是将我的程序更改为:

with open('svm_light/{0}/predictions-{1}'.format(hashtag,segMent)) as f:
    tot_sum = 0
    for i,x in enumerate(f, 1):
         val = float(x)
         tot_sum += val            
         average = tot_sum/i
         print average

打印以下内容:

  @ubuntu:~/Documents/tweets/svm_light$ python2.7 tweetAverage2.py

  0.428908289104
  0.326446277105
  0.63672940322
  0.600035561829
  0.666699795857

它将输出整齐地打印到屏幕上,但我想将其平均每行保存1次,就像在实际输出中显示的那样。
我是python的新手,在ubuntu下使用2.7。

更新

thanx快速响应,介绍了str函数。但是,它打印一个空文件,我可以看到该文件有一些内容,然后它消失了。最有可能的是它一直被覆盖。所以我把这个打印功能放在一边它应该是,但在哪里?

1 个答案:

答案 0 :(得分:3)

在将average写入文件之前,您应该将str()转换为字符串,您可以使用outFile.write(str(average)) 或字符串格式。

file.write

>>> print file.write.__doc__ write(str) -> None. Write string str to file. #expects a string Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. 的帮助:

outFile_name = "svm_light/{0}/predictions-average.txt".format(hashtag)
in_file_name = 'svm_light/{0}/predictions-{1}'.format(hashtag,segMent)
with open(in_file_name) as f, open(outFile_name, 'w') as outFile:
    tot_sum = 0
    for i,x in enumerate(f, 1):
        val = float(x)
        tot_sum += val            
        average = tot_sum/i
        outFile.write(average + '\n') # '\n' adds a new-line  

<强>更新

{{1}}