os.path.exists不接受变量输入

1 python string immutability

每当我调用os.path.exists(变量)时,它将返回false,但如果我调用os.path.exists('/ this/is/my/path'),它将返回true.

import os
import sys

test = None
print("Test directory")
test= sys.stdin.readline()
test.strip('\n')
print(os.path.exists(test))
Run Code Online (Sandbox Code Playgroud)

我知道如果存在权限错误,os.path.exists可以返回false,但我引用的目录没有限制.有时我的路径中有空格.我尝试传递路径,因为'/ this \是/ my/path'和'/ this是/ my/path具有相同的结果.

Fel*_*ing 6

你必须做

test = test.strip("\n")
Run Code Online (Sandbox Code Playgroud)

字符串是不可变的,因此返回一个新字符串.strip()

(至少你的代码适用于我,如果它仍然不适合你,它必须是别的东西.)