python open() 在打开命名中具有 space 的文件时出现错误(即示例 text.txt)

python open() gives me error while opening files having a space in naming(i.e. example text.txt)

当我在 python 中使用 open() 时,它显示 FileNotFound,仅当我尝试打开命名中带有空格的文件时,(例如 text.txt)

我尝试使用 with open('Users/vandit/Desktop/example\ text.txt', 'rb') as f:

'\'只用在shell中,转义后面的space。在 python 中,您可以将整个内容括在引号中: with open('Users/vandit/Desktop/example text.txt', 'w') as f:

此外(如果您使用的是 windows),如果您仍然遇到错误,请尝试在字符串前加上安装 Windows 的驱动器,主要是 C:\ .所以会变成:with open('C:/Users/vandit/Desktop/example text.txt', 'w') as f: