OSError: [Errno 22] Invalid argument: 'path'

OSError: [Errno 22] Invalid argument: 'path'

我想使用 logging 模块。这是我的代码:

from datatime import datatime
import logging
output_dir = fr'./{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}.log'  # fr"" is f"" + r"" 
logging.basicConfig(filename=output_dir, level=logging.DEBUG)
logger = logging.getLogger()

但是当我运行它时,会出现这个错误:

Traceback (most recent call last):
  File "C:\Users\PaliProx\Desktop\Projects\main.py", line 5, in <module>
    logging.basicConfig(filename=output_dir, level=logging.DEBUG)
  File "C:\Users\PaliProx\AppData\Local\Programs\Python\Python39\lib\logging\__init__.py", line 2003, in basicConfig
    h = FileHandler(filename, mode,
  File "C:\Users\PaliProx\AppData\Local\Programs\Python\Python39\lib\logging\__init__.py", line 1146, in __init__ 
    StreamHandler.__init__(self, self._open())
  File "C:\Users\PaliProx\AppData\Local\Programs\Python\Python39\lib\logging\__init__.py", line 1175, in _open    
    return open(self.baseFilename, self.mode, encoding=self.encoding,
OSError: [Errno 22] Invalid argument: 'C:\Users\PaliProx\Desktop\Project\2021-09-09 18:28:27.log'

引发此错误的代码有什么问题?

Windows 文件名中不能有冒号。试试这个:

output_dir = fr'./{datetime.now().strftime("%Y-%m-%d %H%M%S")}.log'