将python输出打印到不工作的文件
我有以下功能将python输出打印到不工作的文件,python,Python,我有以下功能 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
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
它将输出整齐地打印到屏幕上,但我希望每行平均保存一次,就像实际输出中显示的一样。我是python新手,在ubuntu下使用2.7 更新
为了快速响应thanx,引入了str函数。然而,它打印了一个空文件,我可以看到文件有一点内容,然后它就消失了。很可能它一直被覆盖。因此,我将这个打印函数放在不应该放的地方,但放在哪里?在将其写入文件之前,您应该将
average
转换为字符串,您可以使用str()
或字符串格式
outFile.write(str(average))
有关文件的帮助。编写:
>>> 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
outFile.write(str(average)+“\n”)
@RHK-S8以追加模式('a'
)打开outFile
),如果您在循环中写入同一文件。@RHK-S8使用with
语句打开outFile
,您的代码无法工作,因为您没有关闭或刷新outFile
。尝试我的更新代码。我复制了你的代码,它生成一行,平均值为1。而不是多重平均,每line@RHK-我想我没有正确缩进书写部分。但是这里没有多个平均值,您只是在循环结束时计算了一个平均值。没有问题:)请参阅更新,它将5个平均值(输入为5个文件)打印到屏幕上,这就是我想要的文件中的输出。