在做文件读取写入操作的时候遇见OSError: [Errno 22] Invalid argument: 'F:\\pythonProject\\Api\\common\\2022-03-11_15:37:23test.txt'的报错,单独的打印出文件路径明明是正确,但使用python open()函数读写文件时就会报该错误
错误代码:
import os import time now = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) file_path = os.path.realpath(__file__) file_name = os.path.join(os.path.split(file_path)[0], now+'test.txt') with open(file_name, 'w+') as file: print(file)
报错内容如下:
要特别注意,以当前时间命名文件时,时间格式化:"%Y-%m-%d_%H:%M:%S" 修改为"%Y-%m-%d_%H_%M_%S" 就能避免这种错误,注意一定格式化一定不要用冒号:
修改后的代码:
import os import tim