【问题标题】:Refer to dynamic name (a variable name) that is a log file in a Python script在 Python 脚本中引用作为日志文件的动态名称(变量名)
【发布时间】:2015-03-30 15:10:24
【问题描述】:

我想创建一个 Python 脚本来创建一个具有唯一名称的日志文件。如果可能,我希望唯一的名称包含日期时间戳。

我可以用我喜欢的名称创建一个字符串(唯一的带有时间戳):

import os, datetime, copy
lastPart = datetime.datetime.now().strftime('%m/%d/%Y/%s')
logName = 'log' + lastPart + '.txt'
print logName

以上演示了如何创建具有理想日志名称的变量。
我想在整个脚本中写入这个日志文件。我将把各种操作的结果发送到这个日志文件。自然,此日志文件的名称会因运行而异(给定时间戳)。如何在 Python 中基于变量名创建文件?如何在不同行的静态代码中引用它?我想给它写信。我知道 >> 在 Python 中有效。

【问题讨论】:

    标签: python file variables logging dynamic


    【解决方案1】:

    文件名可能不同;

    这并不意味着您需要更改保存文件名的变量的名称。

    import os, datetime, copy
    lastPart = datetime.datetime.now().strftime('%m/%d/%Y/%s')
    logName = 'log' + lastPart + '.txt'
    
    log_file = open(logName, "a")   # in append mode
    
    log_file.write("this is a test\n")
    

    【讨论】:

      【解决方案2】:

      休应该得到荣誉。这是解决方案(因为我的 Linux 版本不喜欢文件名中的斜杠 (/)):

      导入操作系统、日期时间、复制 lastPart = datetime.datetime.now().strftime('%m.%d.%Y.%s') logName = 'log' + lastPart + '.txt'

      log_file = open(logName, "a") # 处于追加模式

      log_file.write("这是一个测试\n")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        相关资源
        最近更新 更多