用户创建的日志文件
user created log files
我得到一个 TypeError: object of type file' has no len()
我已将问题追溯到执行时建立的路径。
我缺少什么来更正 "savePath" 减速或 "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()
整个程序如下,供参考:
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()
这是一个工作版本:
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()
问题中发布的代码片段存在一些问题:
两个导入语句连接在一起。每一个都应该在一个单独的行上。
os.path.join
函数对打开的文件句柄无效。
read()
和 close()
方法缺少括号。
如果目的是读取追加模式写入的内容,则需要通过tell()
和seek()
获取当前文件位置到该位置after写入文件。
虽然在没有任何条件检查的情况下调用 main()
是合法的,但通常最好确保模块作为脚本被调用而不是被导入。
我得到一个 TypeError: object of type file' has no len()
我已将问题追溯到执行时建立的路径。
我缺少什么来更正 "savePath" 减速或 "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()
整个程序如下,供参考:
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()
这是一个工作版本:
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()
问题中发布的代码片段存在一些问题:
两个导入语句连接在一起。每一个都应该在一个单独的行上。
os.path.join
函数对打开的文件句柄无效。read()
和close()
方法缺少括号。如果目的是读取追加模式写入的内容,则需要通过
tell()
和seek()
获取当前文件位置到该位置after写入文件。虽然在没有任何条件检查的情况下调用
main()
是合法的,但通常最好确保模块作为脚本被调用而不是被导入。