[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Writing output of function to a csv file

> On May 25, 2020, at 11:25 AM, MRAB <python at mrabarnett.plus.com <mailto:python at mrabarnett.plus.com>> wrote:
> On 2020-05-25 19:00, Ciar?n Hudson wrote:
>> Hi,
>> In the code below, which is an exercise I'm doing in class inheritance, almost everything is working except outputting my results, which as the function stock_count, to a csv.
>> stock_count is working in the code.
>> And I'm able to open and close the csv called cars, but the stock_count output is not being written to the file.
>> Any suggestions?
> [snip]
>>     def stock_count(self):
>>         print('petrol cars in stock ' + str(len(self.petrol_cars)))
>>         print('electric cars in stock ' + str(len(self.electric_cars)))
>>         print('diesel cars in stock ' + str(len(self.diesel_cars)))
>>         print('hybrid cars in stock ' + str(len(self.hybrid_cars)))
>>              def process_rental(self):
>>         answer = input('would you like to rent a car? y/n')
>>         if answer == 'y':
>>             self.stock_count()
>>             answer = input('what type would you like? p/e/d/h')
>>             amount = int(input('how many would you like?'))
>>             if answer == 'p':
>>                 self.rent(self.petrol_cars, amount)
>>             if answer == 'd':
>>                 self.rent(self.diesel_cars, amount)
>>             if answer == 'h':
>>                 self.rent(self.hybrid_cars, amount)
>>             else:
>>                 self.rent(self.electric_cars, amount)
>>         self.stock_count()
>>                  file = open("cars.csv","w")
>>         file.write(str(self.stock_count()))
>>         file.close()
> In 'stock_count' you're telling it to print to the screen. Nowhere in that function are you telling it to write to a file.

More specifically, your main code calls the dealership.process_rental method.  That method calls self.stock_count() which writes to the screen. 

Then, you are attempting to write the same information to a file.  Your code successfully opens a file, but your next line:
tries to take the output of that self.sock_count() and write that to the file.  Your self.stock_count does not return anything, so it returns the special value: None.  So, the file is created, and the only thing written to the file is None.

Since this is a homework assignment, I won't show you how to do it (I am a teacher).  But you need to format the information that you want to write as a string and write that to a file.