-1

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?

  • 2
    `f.write(output())` will write to the file whatever was _returned_ by the function, not what was printed by the function. If `output` here is `SHIFT_TRAFFIC_OFF`, then it's trying to do `f.write(None)` because `SHIFT_TRAFFIC_OFF` doesn't return anything. – Kevin Mar 06 '18 at 18:32
  • Your SHIFT_TRAFFIC_OFF function prints a string it doesn't return a string. You need to return a string so that f.write can write it to your file. Change your SHIFT_TRAFFIC_OFF to return """ router ospf 1... """ – Ashley Mar 06 '18 at 18:33
  • I understand now... But what would be a nice clean way of doing it? If I have a method that prints - how do I return all that string nicely? – superloopnetworks Mar 06 '18 at 18:43

1 Answers1

0

Your function returns no value; therefore, as Kevin said, it is equivalent to calling 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. Refer to this post for more detail.

Austin A
  • 566
  • 2
  • 15