1、在学习从文件读取数据中,写了个示例代码,读取不在同一个目录的file.txt,运行后报这个Python OSError: [Errno 22] Invalid argument:错误:
(1)、首先,在F盘的python_stu中新增了一个file.txt,同时在F盘的python_stu文件目录底下新增一个file文件夹,里面有个file_reader.py来读取python_stu文件目录底下的file.txt,代码分别如下:
file.txt:
哈哈
呵呵
霍霍
file_reader.py:
with open('F:\python_stu\file.txt') as file_obj:contents = file_obj.read();print(contents.rstrip());
(2)、运行后报错:
(3)、出现这种错误的原因是由于读取不到这个文件,看Traceback报的错误,最后一行,很明显读取不到file.txt,前面的F:\\python_stu没错,后面的名称怎么变了,还是x0cile.txt。
(4)、解决办法,可修改上述第一行代码为:
with open('F:\python_stu/file.txt') as file_obj:
或者:
with open('F:/python_stu/file.txt') as file_obj:
或者:
with open('F://python_stu//file.txt') as file_obj:
又或者:
with open('F:\\python_stu\\file.txt') as file_obj:
还有一些我就不附上了,上面第一种方式不统一,最好不要用,用统一的方式,而且有时候还有注意一些转义字符,比如 \t,\n也会导致报错。
以上内容仅供大家学习参考,谢谢!
![OSError: [Errno 22] Invalid argument错误解决方案](https://img-blog.csdnimg.cn/feba1470f86d40fba4f664e61aab177a.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Yqg5rK55bCP6JCM5YWU,size_20,color_FFFFFF,t_70,g_se,x_16)
![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)







