Nicholas Shaffer Nicholas Shaffer - 3 months ago 21
Python Question

user created log files

I am trying to create log files that is saved in my documents folder upon log in of the system. This is my code... something is going wrong within the

printTime()
function...the issue I am having is getting the .txt file created upon execution saved in the documents folder specified in the code below.

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()

Answer

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.

Comments