首页 > 解决方案 > Python - 如何解决 OSError:[Errno 22] 无效参数

问题描述

我正在学习 python 中的文件对象,但是每当我尝试打开文件时,它都会显示以下错误。

我已经检查过该文件是否在同一目录中并且它存在只有当我将我的文件命名为测试如果我使用任何其他名称时才会出现此错误,那么它可以正常工作这是我的代码

f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')

这是错误

  Traceback (most recent call last):
  File "C:/Users/Tanishq/Desktop/question.py", line 1, in <module>
  f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
  OSError: [Errno 22] Invalid argument: 'C:\\Users\\Tanishq\\Desktop\\python   
  tutorials\test.txt'

标签: pythonfileinvalid-argument

解决方案


您的问题是反斜杠字符,例如\T

尝试:

f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')

Python\用来表示特殊字符。因此,您提供的字符串实际上并不能真正代表正确的文件路径,因为 Python 的解释\Tanishq\与原始字符串本身不同。这是我们放在r它前面的。这让 Python 知道我们确实想要使用原始字符串并将其\视为普通字符。


推荐阅读