0

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
Community
  • 1
  • 1

2 Answers2

2

Change def __append__(s): to def __append__(self, s):

Vor
  • 33,215
  • 43
  • 135
  • 193
  • Traceback (most recent call last): File "add_to_file.py", line 4, in class add_to_file(object): File "add_to_file.py", line 15, in add_to_file __append__("Junk","PQR") File "add_to_file.py", line 14, in __append__ self.data_file.write(s) AttributeError: 'str' object has no attribute 'data_file' – beginer_newbie Jan 31 '15 at 21:45
0

It's unclear what exactly you're trying to accomplish — it looks sort of like a context manager class. I renamed __append__() to append() because methods that start and end with double underscores should only be defined by the language and I renamed your class from add_to_file to AddToFile in accordance with PEP 8 - Style Guide for Python Code.

import os
import sys

class AddToFile(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(self, s):
        self.data_file.write(s)


with AddToFile("Junk") as atf:
    atf.append("PQR")

with open("Junk") as file:
    print(file.read())  # --> PQR
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Thank you, that works fine. Still trying to figure out some basics__beginer_newbie – beginer_newbie Feb 01 '15 at 00:17
  • The most important things that were wrong were calling the `append()` method in the class definition itself and not having an initial `self` argument in its definition. – martineau Feb 01 '15 at 00:29