Hi all,

New python student here. I have been using O¹reilly¹s "Python Beyond the
Basics: Object Oriented Programming video series". In one of the
assignments we are to write a simple inheritance hierarchy of three
classes that write to text files. I have actually written the code for the
assignment and it runs as well as meets the requirements of the
assignment. I am posting to get feedback on how I can improve this and
making it more pythonic and concise.

Please keep in mind that I am simply ³simulating" writing to a log file
and a tabbed delimited file, so I¹m not necessarily looking for which
modules I could have to create actual log files or writing to actual csv
files. The output of the code should be two text files with text written
to them that have been passed to the instance of each respective object.

#!/usr/bin/env python

import abc
import datetime

class WriteFile(object):
    __metaclass__ = abc.ABCMeta
    
    
    @abc.abstractmethod
    def write(self,text):
        """Write to file"""
        return 
    

class LogFile(WriteFile):
    def __init__(self,fh):
    self.fh = fh
        

    def write(self, text):
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    entry = "{0} {1}{2}".format(date, text, '\n')
    with open(self.fh, 'a') as f:
    f.write(entry)

class DelimWrite(WriteFile):
    def __init__(self, fh, delim):
    self.fh = fh
    self.delim = delim
        

    def write(self, text):
    with open(self.fh, 'a') as f:
        entry = ""
        for item in text:
            if self.delim in item:
                entry += ' "{0}"{1} '.format(item,self.delim)
            else:
                entry += item+self.delim
        f.write(entry.strip(self.delim) + '\n')
            
            
            

if __name__ == "__main__":
    
    
    log = LogFile('log.txt')
    log.write('This is a log message')
    log.write('This is another log message')
    
    
    d = DelimWrite('test.csv',',')
    d.write([Œ1¹,¹2¹,¹3¹])
    d.write(['a','this, that','c¹])    #Double quote item if delimiter
included as list item
    d.write([Œbasketball¹,'football¹,'golfball'])




_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to