[英]Writing to file not working in Python
I'm having issues writing to a text file.我在写入文本文件时遇到问题。 The first file gets created but there are no text that is written.
创建了第一个文件,但没有写入任何文本。 Here is my code:
这是我的代码:
def write2file(self):
generate_file = ['SHIFT_TRAFFIC_OFF','REMOVE_ADD_BUNDLE','SHIFT_TRAFFIC_ON']
for method in generate_file:
f = open("/home/superloop/10gto100g/test/%s_%s" % (self.hostname,method), "w")
output = getattr(self,method)
# self.SHIFT_TRAFFIC_OFF()
f.write(output())
f.close()
def SHIFT_TRAFFIC_OFF(self):
print "router ospf 1"
print " area 0"
print " interface Bundle-Ether%s" % self.bundle
print " cost 100"
print "!"
print "router ospfv3 1"
print " area 0"
print " interface Bundle-Ether%s" % self.bundle
print " cost 100"
And here is the output when I execute the application:这是我执行应用程序时的输出:
router ospf 1
area 0
interface Bundle-Ether4
cost 100
!
router ospfv3 1
area 0
interface Bundle-Ether4
cost 100
Traceback (most recent call last):
File "main.py", line 42, in <module>
main()
File "main.py", line 20, in main
parse_engine(database)
File "/home/superloop/10gto100g/parser.py", line 15, in parse_engine
device = BaseDevice(list[0],list[1],list[2],list[3],list[4])
File "/home/superloop/10gto100g/objects/basedevice.py", line 12, in __init__
self.write2file()
File "/home/superloop/10gto100g/objects/basedevice.py", line 20, in write2file
f.write(output())
TypeError: expected a character buffer object
What is going on here?这里发生了什么?
Your function returns no value;你的函数没有返回值; therefore, as Kevin said, it is equivalent to calling f.write(None).
因此,正如凯文所说,相当于调用了 f.write(None)。
In regards to your comments, you can do the following...关于您的评论,您可以执行以下操作...
import sys
sys.stdout = open({FILENAME}, "w")
print ("this will be written to the file")
This redirects stdout to your file, make sure you reset it back by calling:这会将标准输出重定向到您的文件,请确保通过调用将其重置:
sys.stdout = sys.__stdout__
after you finish whatever you are doing.在你完成你正在做的事情之后。 I'm fairly sure that this will fix the problem, but I haven't tested it.
我相当确定这会解决问题,但我还没有测试过。
As well, it looks like you're using an older version of Python, so you may have to use a slightly different methodology.同样,看起来您使用的是旧版本的 Python,因此您可能需要使用稍微不同的方法。 Refer to this post for more detail.
有关更多详细信息,请参阅此帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.