Here is my python code. I am attempting to create a class that does file manipulation. I used similar structure as in this URL but I am unable to append to a file.
add_to_file.py-----------
import os
import sys
class add_to_file(object):
def __init__(self, filename):
self.data_file = open(filename,'a')
def __enter__(self): # __enter__ and __exit__ are there to support
return self # `with self as blah` syntax
def __exit__(self, exc_type, exc_val, exc_tb):
self.data_file.close()
def __iter__(self):
return self
def __append__(s):
self.data_file.write(s)
__append__("PQR")
add_to_file("Junk")
Result-------------------
Traceback (most recent call last):
File "add_to_file.py", line 4, in <module>
class add_to_file(object):
File "add_to_file.py", line 15, in add_to_file
__append__("PQR")
File "add_to_file.py", line 14, in __append__
self.data_file.write(s)
NameError: global name 'self' is not defined