Gal*_*are 2 python file-io python-2.7
我试图为Python创建一个无法正常工作的日志记录模块,因为它无法创建文件对象.
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()
Run Code Online (Sandbox Code Playgroud)
fil不会None
像我得到的那样工作AttributeError
.我也试过创建一个虚拟对象:
fil = open("dummy.tmp","w+")
Run Code Online (Sandbox Code Playgroud)
但是dummy.tmp
文件被写入,即使init()
之前log()
被调用了.显然,您无法在已打开的文件上打开新文件.我试图关闭fil
之前init()
,但Python说它无法write()
在关闭的文件上执行.
这是正在访问的代码 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!")
Run Code Online (Sandbox Code Playgroud)
我想登录我的程序,我找不到解决方法.
您的问题是您没有分配给全局fil
:
def init(fname):
fil = open(fname, 'w+')
Run Code Online (Sandbox Code Playgroud)
这将创建一个名为的新局部变量fil
.
如果要分配给全局变量fil
,则需要将其放入本地范围:
def init(fname):
global fil
fil = open(fname, 'w+')
Run Code Online (Sandbox Code Playgroud)