【问题标题】:Python -How to solve OSError: [Errno 22] Invalid argumentPython - 如何解决 OSError:[Errno 22] 无效参数
【发布时间】:2020-07-31 15:37:01
【问题描述】:

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

【问题讨论】:

  • 您需要转义字符串中的所有\ s 或使用raw string(即r'...'
  • 在字符串前放置一个r 并去掉双反斜杠。
  • 您必须转义所有反斜杠 ('C:\\\\Users\\Tanishq\\Desktop\\python tutorials\\test.txt') 或使用原始字符串文字 (r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt')。
  • 谢谢...帮助

标签: python file invalid-argument


【解决方案1】:

您的问题是与 \T 等反斜杠字符有关:

试试:

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

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

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多