Python - 如何解决 OSError: [Errno 22] 无效参数的问题

8

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

我已经检查过文件在同一个目录中存在。如果我将文件命名为“test”,则会出现此错误。使用其他名称则可以正常工作。下面是我的代码:

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'

1
你需要转义字符串中所有的 \,或者使用 原始字符串(即 r'...')。 - 0x5453
在字符串前加上“r”,并删除双反斜杠。 - Klaus D.
1
你必须要么转义所有反斜杠 ('C:\\\\Users\\Tanishq\\Desktop\\python tutorials\\test.txt'),要么使用原始字符串字面值 (r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt')。 - Gevorg Davoian
谢谢...它有所帮助 - Tanishq Trivedi
1个回答

13

您的问题在于反斜线字符,例如 \T

请尝试使用以下方法:

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

Python使用\来表示特殊字符。因此,你提供的字符串实际上并不能真正代表正确的文件路径,因为Python将会以不同于原始字符串本身的方式解释\Tanishq\。这就是为什么我们在它前面放置了r。这让Python知道我们确实希望使用原始字符串,并将\视为普通字符。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接