Python: Creating an empty file object

17,830

Solution 1

Your problem is that you don't assign to the global fil:

def init(fname):
    fil = open(fname, 'w+')

This creates a new local variable called fil.

If you want to assign to the global variable fil you need to bring it into the local scope:

def init(fname):
    global fil
    fil = open(fname, 'w+')

Solution 2

If you want to MAKE your own logging module, then you may want to turn what you already have into a class, so you can import it as a module.

#LoggerThingie.py
import os
import datetime



class LoggerThingie(object):
    def __init__(self,fname):
         self.fil = open(fname, 'w+')
         self.fil.write("# PyIDE Log for" + str(datetime.datetime.now()))

    def log(self,strn):
        currentTime = datetime.datetime.now()
        self.fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
        print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn

    def halt(self):
        self.fil.close()

If you did this as a class, you would not have to keep track of globals in the first place (which is generally understood as bad practice in the world of programming: Why are global variables evil? )

Since it is now a module on its own, when you want to use it in another python program you would do this:

from LoggerThingie import LoggerThingie
#because module filename is LoggerThingie.py and ClassName is LoggerThingie

and then use it wherever you want, for example:

x = LoggerThingie('filename.txt') #create LoggerThingie object named x

and every-time you want to insert logs into it:

x.log('log this to the file')

and when you are finally done:

x.halt() # when ur done
Share:
17,830
Galen Nare
Author by

Galen Nare

Python and Java programmer. Gamer.

Updated on July 10, 2022

Comments

  • Galen Nare
    Galen Nare almost 2 years

    I am attempting to make a logging module for Python that does not work because it fails on creation of the file object.

    debug.py:

    import os
    import datetime
    import globals
    
    global fil
    fil = None
    
    def init(fname):
         fil = open(fname, 'w+')
         fil.write("# PyIDE Log for" + str(datetime.datetime.now()))
    
    def log(strn):
        currentTime = datetime.datetime.now()
    
        fil.write(str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn)
        print str(currentTime) + ' ' + str(os.getpid()) + ' ' + strn
    
    def halt():
        fil.close()
    

    fil will not work as None as I get an AttributeError. I also tried creating a dummy object:

    fil = open("dummy.tmp","w+")
    

    but the dummy.tmp file is written to instead, even though init() is called before log() is. Obviously you cannot open a new file over an already opened file. I attempted to close fil before init(), but Python said it could not perform write() on a closed file.

    This is the code that is accessing debug.py

    if os.path.exists(temp):
             os.rename(temp, os.path.join("logs","archived","log-" + str(os.path.getctime(temp)) + ".txt"))
             debug.init(globals.logPath)
             debug.log("Logger initialized!")
    

    I would like to have logging in my program and I cannot find a workaround for this.