Python - 如何解决 OSError: [Errno 22] Invalid argument

Tan*_*edi 8 python file invalid-argument

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

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

f = open('C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Run Code Online (Sandbox Code Playgroud)

这是错误

  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'
Run Code Online (Sandbox Code Playgroud)

M Z*_*M Z 13

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

尝试:

f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Run Code Online (Sandbox Code Playgroud)

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