Leem.fin
Leem.fin

Reputation: 42602

write to file in python

I might ask a stupid question. I just started learning Python.

I have a simple python script, which defined a class with two methods: add_course and write_to_file:

class School:
    courses=["Math","Physics","Chemical"]

    def __init__(self):
        return

    def add_course(self, course):
        if course not in self.course:
           self.course.append(course)

    def write_to_file():
        course_file = open('courses.csv', 'w+')
        wr = csv.writer(course_file, delimiter='\t')
        writer.writerow(self.courses)

// create a School instance
school = School()

// add course
school.add_course("test")
school.add_course("test2")
school.add_course("test")

// write course to file
school.write_to_file()

I run the above script, then, I open the courses.csv file, I don't see "test" and "test2", but I can see the courses "Math","Physics","Chemical" Why?

Upvotes: 0

Views: 1254

Answers (2)

AlokThakur
AlokThakur

Reputation: 3741

I found few mistakes in your code snippet, As you are new to Python, So thought of posting working code-

class School:
    courses=["Math","Physics","Chemical"]

    def __init__(self):
        return

    def add_course(self, course):
        if course not in self.courses:
           self.courses.append(course)

    def write_to_file(self):
        with open('courses.csv', 'w+') as course_file:
        wr = csv.writer(course_file, delimiter='\t')
        wr.writerow(self.courses)

My changes-

1. def write_to_file(self)
2.if course not in self.courses:
               self.courses.append(course)
3. wr.writerow(self.courses)

Upvotes: 0

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

Currently you have added courses as class-level attribute, but trying to access it as instance attribute, so you have to move courses initialization into __init__ method as in code snippet below:

def __init__(self):
    self.courses = ["Math", "Physics", "Chemical"]

Also you have to modify add_course method to append item into self.courses and not to self.course:

def add_course(self, course):
        if course not in self.courses:
           self.courses.append(course)

See SO Python: Difference between class and instance attributes question for more explanations of how and when each type of attributes shall be used.

Upvotes: 5

Related Questions