簡體   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