简体   繁体   English

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

[英]print python output to file not working

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. 我只是试图将每个平均值的输出打印到每行1个平均值。 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. 它将输出整齐地打印到屏幕上,但我想将它平均每行保存1次,就像在实际输出中显示的那样。
Im new to python, and am using 2.7 under ubuntu. 我是python的新手,我在ubuntu下使用2.7。

UPDATE UPDATE

thanx to a quick response, introduced the str function. thanx快速响应,介绍了str函数。 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. 您应该在将average转换为文件之前将其转换为字符串,您可以使用str()或字符串格式。

outFile.write(str(average)) 

Help on file.write : 有关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  

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

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