繁体   English   中英

Python:写入文本文件

[英]Python: writing to a text file

我希望我的代码将某些错误写入文本文件。 它正在复制文件,我想将“未复制”的文件写到文本文件中进行记录。 每当脚本遇到错误时,我都会在脚本中附加一个包含文件路径的数组(如下所示):

errors.append(srcfile)

循环后,我有以下代码,我认为该代码会将路径写入文本文件:

text_file = open("%s_copy_log.txt" % username, "a")
for line in errors:
    text_file.write(line)
text_file.close()

我想念什么吗?

这是一个XY问题的示例:您想要做一些事情,想出一个解决方案,找到该解决方案的问题,然后寻求帮助。 我假设尽管您可以自己记录日志(如您所尝试的),但是使用Python内置的记录器将更有意义。 他们已经完成了您所需的大部分工作,您所需要做的就是导入,配置和使用它。

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

example.log:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

这还支持命令行日志记录级别设置等功能。

文档 教程

尝试将a更改为a+ ,告诉python创建一个不存在的文件。

text_file = open("%s_copy_log.txt" % username, "a+")

进一步阅读Python文件IO类型

我不确定您的应用程序结构是什么样子,但是如果您有许多用户,并且希望每个用户名都有自己的日志(为什么?),那么最好的方法可能是:

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
admin_handler = logging.FileHandler("app.log")
admin_handler.setLevel(logging.DEBUG)
logger.addHandler(admin_handler)
# this will write ALL events to one location
user_logger = logger.getChild("userlog")

def login(username, password):
    if verify(username, password):  # however you're doing this
        user_logger.addHandler(logging.FileHandler("%s.log" % username))
        user_logger.setLevel(logging.WARNING)  # or maybe logging.INFO?
        user_logger.info("%s logged in" % username)

        # authenticate the user as you currently do
    else:
        logger.warning("%s attempted login with bad password!" % username)

        # prompt the user as you currently do

def logout():
    user_logger.handlers = []  # remove previous user logger

    # de-authenticate as normal

def user_log_something(the_thing):
    if the_thing.is(something_critical):
        user_logger.critical(the_thing)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM