我正在使用一个功能来测试用户输入的目录是否有效。用户输入不转到文件名,而仅转到文件夹名,例如"C:/Users/username/Desktop/folder"
。因此,我编写了以下函数来获取路径/目录:
def get_path():
while True:
file_path = input("Please enter file path (up to folder level); q to quit:> ")
print(repr(file_path))
if os.path.isdir(file_path):
return file_path
elif file_path.lower() == 'q':
sys.exit()
else:
print("The path you entered is invalid.")
continue
但是,即使我在cmd中运行os.path.isdir()时输入的路径/字符串有效,它也始终显示The path you entered is invalid.
。
在Win10 cmd上运行该功能会产生以下结果
>>> import sys
>>> import os
>>> import pathlib
>>> def get_path():
... while True:
... file_path = input("Please enter file path (up to folder level); q to quit:> ")
... print(repr(file_path))
... if os.path.isdir(file_path):
... return file_path
... elif file_path.lower() == 'q':
... sys.exit()
... else:
... print("The path you entered is invalid.")
... continue
...
>>> path = get_path()
Please enter file path (up to folder level); q to quit:> "C:/Users/myname/Desktop/"
'"C:/Users/myname/Desktop/"'
The path you entered is invalid.
Please enter file path (up to folder level); q to quit:> "C:/Users/myname/Desktop/randomprojects"
'"C:/Users/myname/Desktop/randomprojects"'
The path you entered is invalid.
Please enter file path (up to folder level); q to quit:>