Python记录:使用文件模式"w"时覆盖而不是附加 [英] Python Logging: Overwriting instead of Appending when using filemode "w"

查看:90
本文介绍了Python记录:使用文件模式"w"时覆盖而不是附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,每60秒运行一次.

I have a Python script that runs every 60 seconds.

在此脚本中,我有一个打印消息的方法,并将其附加到 1882.log :

Within this script, I have a method that prints a message, as well as appending it to 1882.log:

import praw
import os
import logging
from time import gmtime, strftime

logging.basicConfig(filename="1882.log", filemode="w", level=logging.INFO)

def log_it(s):
    o = strftime("%Y-%m-%d %H:%M:%S", gmtime()) + " GMT > " + s
    logging.info(o)
    print(o)

它在其他方法中被调用,如下所示:

It is called within other methods like so:

log_it("Message here!")
# "2019-08-28 17:31:31 GMT > Message Here!"

我正在尝试将每条消息追加到现有历史记录中,但是每次脚本运行时,日志文件 1882.log 都会被覆盖,这意味着日志历史记录只是在上次运行中输出的消息,而并非所有运行.

I am trying to append each message to the existing history, however each time the script runs, the log file 1882.log is somehow overwritten, meaning that the log history is only the messages output in the last run, and not all runs.

我了解到 filemode ="w" 将打开文件以进行附加操作,而不是覆盖文件,因此我对每次运行此脚本时为何文件被完全覆盖感到困惑

I understood that the filemode="w" will open the file for appending, and not overwriting, so I'm confused as to why the file is being overwritten completely each time I run this script.

为什么会这样?

推荐答案

使用模式 filemode ="a" 进行附加.根据 logging.basicConfig 也应该是默认值:

Use mode filemode="a" for appending. According to the docs for logging.basicConfig that should also be the default:

文件模式-如果指定了文件名,请在此

filemode - If filename is specified, open the file in this mode. Defaults to 'a'.

您可以在指向文档的链接处查看所有可用文件模式的概述:

You can see an overview of all available filemodes at that link to the docs:

...

'w'-打开以进行写入,首先将文件截断

'w' - open for writing, truncating the file first

...

'a'-打开以进行写入,如果存在则追加到文件末尾

'a' - open for writing, appending to the end of the file if it exists

...

来源: https://docs.python.org/3/library/functions.html#filemodes

这篇关于Python记录:使用文件模式"w"时覆盖而不是附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆