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也会导致报错。

以上内容仅供大家学习参考,谢谢!

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐