Python -How to solve OSError: [Errno 22] Invalid argument

Python -How to solve OSError: [Errno 22] Invalid argument

我正在学习 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'

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

尝试:

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

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