【问题标题】:new file name each time python run每次 python 运行时的新文件名
【发布时间】:2015-08-04 03:04:38
【问题描述】:

使用 python 2.7..

我在下面使用将所有打印输出发送到一个名为 output.log 的文件。每次运行时如何将其发送到不同的文件...在 bash 中,我们可以声明一个名为 date 或其他内容的变量,并拥有文件名的那部分...那么我如何使用 python 实现相同的功能?

所以我的问题是..

  1. 每次我运行以下脚本时,我的文件都应该有一个 output_date/time.log 的命名约定
  2. 我如何删除超过 X 天且文件命名约定为 output_*.log 的文件

    import sys
    f = open('output.log', 'w')
    sys.stdout = f
    print "test"
    f.close()
    

【问题讨论】:

标签: python python-2.7


【解决方案1】:

由于个人对格式的偏好,这通常是我所做的。

import time
moment=time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime())
f = open('output'+moment+'.log', 'w')

就自动删除而言,您希望在运行测试时将其删除吗?

os.remove(fileStringName)

有效,您只需要进行算术和字符串转换。我会使用 os.listdir(pathToDirWithOutputLogs) 遍历文件名并对它们进行数学运算并在旧文件上调用 os.remove。

【讨论】:

    【解决方案2】:

    获取日期/时间:

    from time import gmtime, strftime
    
    outputFileName = "output_#.log"
    outputFileName = outputFileName.replace("#", strftime("%Y-%m-%d_%H:%M:%S", gmtime()))
    

    对于数值递增:

    outputFileName = "output #.log"
    outputVersion = 1
        while os.path.isfile(outputFileName.replace("#", str(outputVersion))):
            outputVersion += 1
        outputFileName = outputFileName.replace("#", str(outputVersion))
    

    要删除某个日期之前的文件,您可以使用 `` 遍历目录中的所有文件,并使用 os.remove() 删除它们。解析后可以compare the file names

    lastTime = "2015-08-03_19:04:41"
    for fn in filter(os.path.isfile, os.listdir()):
        strtime = fn[fn.find("_"):fn.rfind(".")]
        if strtime < lastTime:
            os.remove(fn)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多