Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write the output of a class method to a file in Python?

I’ve been following Python tutorials on YouTube for the past couple of days now, and have made it to an OOP section. The example code has two modules, client.py and car.py. Within car.py is a class called Car, with attributes for the make, model, color (all strings), and year (integer). I decided to expand on the example code to challenge myself and implemented a method called car_print which prints the aforementioned information to the console, but as of right now it isn’t working.

I’m trying to write the results of car_print to a file "car.txt" in my main module, but am getting the following error: file.write(my_car.car_print()), TypeError: write() argument must be str, not None, where my_car is an object of class Car. The only place my code contains None is within car_clear, a method designed to reset the Car object to an empty state where each attribute is set to None. car_print works as expected when called; the issue only arises when trying to write the output to a file.

Here are the contents of client.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from car import Car

make = input("Enter the make of the car: ").capitalize()
model = input("Enter the model of the car: ").capitalize()
year = int(input("Enter the year of the car: "))
color = input("Enter the color of the car: ").capitalize()

my_car = Car(make, model, year, color)

with open('car.txt', 'w') as file:
    file.write(my_car.car_print())

as well as car.py:

class Car:
    # Class constructor-------------------------------------------------------------------------
    def __init__(self, make, model, year, color):
        self.make = make
        self.model = model
        self.year = year
        self.color = color

    # Access functions--------------------------------------------------------------------------
    def get_make(self):  # returns make
        print(self.make)

    def get_model(self):  # returns model
        print(self.model)

    def get_color(self):  # returns color
        print(self.color)

    def get_year(self):  # returns year
        print(str(self.year))

    # Manipulation procedures-------------------------------------------------------------------
    def set_make(self, make):  # overwrites self.make with make
        self.make = make

    def set_model(self, model):  # overwrites self.model with model
        self.model = model

    def set_color(self, color):  # overwrites self.color with color
        self.color = color

    def set_year(self, year):  # overwrites self.year with year
        self.year = year

    # Other functions---------------------------------------------------------------------------
    def car_print(self):  # prints all attributes of car object
        print(self.make)
        print(self.model)
        str(print(self.year))
        print(self.color)

    # def car_clear(self):  # resets car object to empty state
    #     self.make = None
    #     self.model = None
    #     self.year = None
    #     self.color = None

>Solution :

When using the print() function in python you actually print that output to the terminal. In order to use the ‘file.write(string)’ function you must return a string from the function. Your new code should look a bit like this:

def get_make(self):  # returns make
        return self.make

Now the string will get passed to the file.write() by the return keyword.

For your larger car_print() function you will need to add the different variables together, I like f strings to do this. It would look something like this:

def car_print(self):  # prints all attributes of car object
        return f"{self.make}, {self.model}, {self.year}, {self.color}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading