最后重命名日志文件

Renaming the log file at the end

在程序的开头,日志文件被命名为:

filename='D://my_code_3/logging/'+timestr+'_XFR.log'

###set up logging to file
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',datefmt='%m-%d %H:%M',filename='D://my_code_3/logging/'+timestr+'_XFR.log', filemode='w')

在程序执行期间,会在此日志文件中生成各种条目。

在程序结束时,需要重命名日志文件,以包含程序捕获的唯一str变量(str9)(在程序执行开始时最初不可用) ,刚刚创建日志文件时)。为了在程序结束时重命名日志文件,必须首先关闭 old_name 日志文件。我将这些说明包含在以下代码中:

fh = open('D://my_code_3/logging/'+timestr+'_XFR.log', "r")
print fh.read()
fh.close()

然后在最后,我要求重命名如下:

old_file ='D://my_code_3/logging/'+timestr+'_XFR.log'
new_file = 'D://my_code_3/logging/'+timestr+''+str9+'_XFR.log'
os.rename(old_file, new_file)

我收到以下错误消息:

`

Traceback (most recent call last): File "qar_xfr_2017_10_05_WIP.py", line 283, in os.rename(old_file, new_file) WindowsError: [Error 32] The process cannot access the file because it is being used by another process`

我认为 old_file 仍在写入,因此显示文件已打开的消息。如果是这样,我如何在尝试重命名 old_file 之前提供时间延迟?

提前感谢您纠正/建议解决方案。

需要通过调用

正确关闭所有处理程序
logging.shutdown()

之后您可以重命名日志文件。