在做文件读取写入操作的时候遇见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 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)
执行结果如下:

![OSError: [Errno 22] Invalid argument问题解决](https://img-blog.csdnimg.cn/20200403111734408.png)

![已解决OSError: [Errno 22] Invalid argument](https://img-blog.csdnimg.cn/a74f7d5d03234f7c8a635562034442a0.gif#pic_center)
![OSError: [WinError 1455] 解决方案](https://img-blog.csdnimg.cn/3a67c6efe22d43df9cf8b90f38064cd5.png)
![Python文件操作错误:OSError: [Errno 22] Invalid argument(关于Windows下文件名中的敏感字符)](https://img-blog.csdnimg.cn/f2da28ea0a0049db886f6fdcaad3fdb3.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAWWFZMTM4MTYu,size_20,color_FFFFFF,t_70,g_se,x_16)








