python如何拼接时间戳到写入的文件名中

问题描述:

  记录一下拼接文件名时间戳的过程,回顾下可能的问题所在,希望能帮到同样碰到这类问题的兄dei。

  进行单元测试时,最后使用HTMLTestRunner生成的HTML分析报告,需要添加一个时间戳来辨别,但是我写好后,一直报错:

if __name__ == '__main__':
    suite = unittest.TestSuite()
    tests = [TestCase("test_check_res")]
    suite.addTests(tests)
    now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())).decode('utf-8')
    print now, type(now)
    filename = setting.CASE_PATH + now + "result.html"  # CASE_PATH是获取的当前目录的绝对路径
    with codecs.open(filename, 'w', 'utf8') as f:
        runner = HTMLTestRunner.HTMLTestRunner(stream=f, title='Test Report', description='HTMLTestRunner.',verbosity=2)
        runner.run(suite)

  报错情况为:

E:huang	estunit_test>py -2 testing.py
Traceback (most recent call last):
  File "testing.py", line 43, in <module>
    open(filename, 'wb')
IOError: [Errno 22] invalid mode ('wb') or filename: 'E:\huang\test\2019-08-13 22:16:43 testing12345.html'

解决步骤:

1、真的是搜了好久的:IOError: [Errno 22] invalid mode ('wb') or filename:这段报错信息,大家的回复都是转义字符的问题:  

  • The following reserved characters:

    • < (less than)
    • > (greater than)
    • : (colon)
    • " (double quote)
    • / (forward slash)
    • (backslash)
    • | (vertical bar or pipe)
    • ? (question mark)
    • * (asterisk)

2、仔细瞅瞅我的代码,"%Y-%m-%d %H:%M:%S"中的:有问题,故修改为:

    now = str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))

完美解决,生成的文件名称为:20190813221814 testing12345.html

3、拼接需注意的事项:

  1)路径在前,时间戳、名称等在后

  2)不能含有以上列表中的特殊字符

  3)要写入特定编码的文本文件,请效仿codecs的示例,写入unicode,由codecs自动转换成指定编码。

原文地址:https://www.cnblogs.com/wangxue533/p/11349152.html