打开无效参数窗口

时间:2016-09-12 23:52:57

标签: python windows file

import datetime
import os
import sys
import time

if "ZLOG_FILE" not in globals():
    global ZLOG_FILE
    script_dir = os.path.realpath(sys.argv[0]).replace(sys.argv[0], "")
    ZLOG_FILE = os.path.join(script_dir, "log", datetime.datetime.fromtimestamp(time.time()).strftime("%m-%d-%Y %H:%M:%S"))
    with open(ZLOG_FILE, "w"):
        pass

def log(level, msg):
    with open(ZLOG_FILE, "a") as f:

        # Fix colors
        if level == "INFO":
            msg = "ESC[37m[INFO] " + msg

        elif level == "WARN":
            msg = "ESC[33m[WARN] " + msg

        elif level == "ERROR":
            msg = "ESC[31m[ERROR] " + msg

        if level != "ERROR":
            print(msg)
        else:
            sys.stderr.write(msg)
        f.write(msg)

我创建了这个简单的日志库,在第一次导入时,在一个日志目录中创建一个当前时间和日期的新文件,该文件与正在运行的主脚本位于同一位置。但是我得到以下错误:

Traceback (most recent call last):                                              
  File "test.py", line 1, in <module>                                           
    import zlog                                                                 
  File "C:\Users\zane\Desktop\zlog.py", line 10, in <module>                    
    with open(ZLOG_FILE, "w"):                                                  
OSError: [Errno 22] Invalid argument: 'C:\\Users\\zane\\Desktop\\log\\09-12-2016
 20:02:26'                                                                      

我做错了什么?

编辑:使用script_dir变量删除脚本名称,并修复if语句的格式。我仍然得到一个错误

1 个答案:

答案 0 :(得分:0)

Windows无法在文件名中使用冒号,我忘记在获取目录后将路径中的主脚本删除