Skip to main content
 首页 » 编程设计

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

2025年05月04日16虾米哥

每当我调用 os.path.exists(variable) 时它会返回 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)) 

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

请您参考如下方法:

你必须做

test = test.strip("\n") 

字符串是不可变的,所以 strip() 返回一个新字符串。

(至少你的代码对我有用,如果它仍然不适合你,那一定是其他原因。)