1

i have the following function

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)  

I'm simply trying to print the output for each average to 1 average per line. however im getting the following error...

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

if I simply change my program to this:

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

prints the following:

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

  0.428908289104
  0.326446277105
  0.63672940322
  0.600035561829
  0.666699795857

it prints the output neatly to the screen, but i would like to save it 1 average per line, much like is showing in the actual output.
Im new to python, and am using 2.7 under ubuntu.

UPDATE

thanx to a quick response, introduced the str function. However, it prints an empty file, i can see the file has contents for a bit, and then its gone. most likely its being overwritten the whole time. So im placing this print function somehwere it shouldnt be, but where?

4

1 回答 1

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  
于 2013-06-07T17:50:00.637 回答