pythonlogfiles

user created log files


I am getting a TypeError: object of type file' has no len() I have traced down the issue to the path established upon execution.

What am I missing to correct this error found within the "savePath" deceleration or usage within the "temp = os.path.join(savePath, files)"?

def printTime(time):
    savePath = "C:\Users\Nicholas\Documents"
    files = open("LogInLog.txt", "a")
    temp = os.path.join(savePath, files)
    files.write("A LogIn occured.")
    files.write(time)
    print files.read
    files.close

main()

The whole program is below for reference:

from time import strftime
import os.path

def main():
    getTime()

def getTime():
    time = strftime("%Y-%m-%d %I:%M:%S")
    printTime(time)

def printTime(time):
    savePath = "C:\Users\Nicholas\Documents"
    files = open("LogInLog.txt", "a")
    temp = os.path.join(savePath, files)
    files.write("A LogIn occured.")
    files.write(time)
    print files.read
    files.close

main()

Solution

  • Here's a working version:

    from time import strftime
    import os.path
    
    def main():
        getTime()
    
    def getTime():
        time = strftime("%Y-%m-%d %I:%M:%S")
        printTime(time)
    
    def printTime(time):
        savePath = "C:\Users\Nicholas\Documents"
        logFile = "LogInLog.txt"
        files = open(os.path.join(savePath, logFile), "a+")
        openPosition = files.tell()
        files.write("A LogIn occured.")
        files.write(time)
        files.seek(openPosition)
        print(files.read())
        files.close()
    
    if __name__ == '__main__':
        main()
    

    There were a few problems with the code snippet posted in the question:

    1. Two import statements were concatenated together. Each should be on a separate line.

    2. The os.path.join function doesn't work on an open filehandle.

    3. The read() and close() methods were missing parens.

    4. If the intent is to read what is written in append mode, it's necessary to get the current file position via tell() and seek() to that position after writing to the file.

    5. While it's legal to call main() without any conditional check, it's usually best to make sure the module is being called as a script as opposed to being imported.