繁体   English   中英

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

[英]print python output to file not working

我有以下功能

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。

UPDATE

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

您应该在将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  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM