python - 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'
解决方案
您的问题是反斜杠字符,例如\T
:
尝试:
f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r')
Python\
用来表示特殊字符。因此,您提供的字符串实际上并不能真正代表正确的文件路径,因为 Python 的解释\Tanishq\
与原始字符串本身不同。这是我们放在r
它前面的。这让 Python 知道我们确实想要使用原始字符串并将其\
视为普通字符。
推荐阅读
- c# - 如何上下左右拖动统一对象。?
- javascript - 使用递归更改笔触颜色
- graphhopper - 启用混合模式的 Graphhopper 抛出 IllegalStateException
- javascript - PHP JavaScript 刷新某些 div
- php - 使用 PHP-FPM 时在 Laravel 刀片中获取未定义的变量
- batch-file - 仅使用第一个字符的批处理文件 IF 语句
- google-apps-script - 通过 DriveApp 创建的文档副本无法通过 DocumentApp 访问
- php - SOAP 请求适用于 Postman,而不适用于 PHP
- javascript - 更新 HTML 文件文件夹中的所有 href 锚链接
- php - 使用 Godaddy 共享主机和 VPS 服务器配置 Apache solr 4.5.1