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?
You should convert average
to a string before writing it to a file, you can use str()
or string formatting for that.
outFile.write(str(average))
Help on 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.
Update:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.