【问题标题】:python with open invalid argument windows带有打开无效参数窗口的python
【发布时间】:2016-09-12 23:52:57
【问题描述】:
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 语句的格式。我仍然收到错误

【问题讨论】:

  • 您将test.py 视为一个目录,但它可能不是。 (它就在错误消息中。你怎么会错过它?)
  • 您的错误逻辑没有意义。 “如果级别是错误那么,如果级别不是错误?”
  • log 子目录是否存在?如果没有,您将不得不创建它。 open() 不会自动创建缺少的子目录。
  • 它存在,我手动进行了测试。我会添加一种方法来最终自动生成它
  • 也许 Windows 反对文件名中存在冒号?

标签: python windows file


【解决方案1】:

Windows 不能在文件名中使用冒号,并且一旦我得到它所在的目录,我就忘记从路径中删除主脚本

【讨论】:

  • 您的系统驱动器可能是 NTFS,为此保留一个冒号以指定 :stream_name:stream_type 形式的 file stream。打开 NTFS 文件实际上是打开匿名数据流,即::$DATA。打开 NTFS 目录实际上是打开 $I30 索引流,即:$I30:$INDEX_ALLOCATION。目录也可以命名为$DATA 流。在这种情况下,“09-12-2016 20:02:26”是无效的,因为它尝试使用未知的流类型“26”创建一个名为“02”的流。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
相关资源
最近更新 更多