Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:使用os模块检查目录是否存在_Python_Python 3.x_Validation_Input_Python Os - Fatal编程技术网

Python:使用os模块检查目录是否存在

Python:使用os模块检查目录是否存在,python,python-3.x,validation,input,python-os,Python,Python 3.x,Validation,Input,Python Os,我试图使用操作系统模块验证作为用户输入接收的目录是否存在 这就是我接受输入的方式: directory = input("Hi ! \n please type a directory, thanks !") 我的想法是,我想确保用户将键入一个现有的目录,而不是其他任何内容 from pathlib import Path def is_valid_directory(filename): p = Path(filename) return p.exists() and p.

我试图使用操作系统模块验证作为用户输入接收的目录是否存在

这就是我接受输入的方式:

directory = input("Hi ! \n please type a directory, thanks !")
我的想法是,我想确保用户将键入一个现有的目录,而不是其他任何内容

from pathlib import Path

def is_valid_directory(filename):
    p = Path(filename)
    return p.exists() and p.is_dir()
pathlib
是一个非常方便的模块,用于处理任何类型的文件路径。
p.exists()
调用是多余的,因为
p.is_dir()
对于不存在的路径返回
False
,但如果同时选中这两个选项,则可以提供更好的错误消息


编辑:注意,
pathlib
是在Python3.4中添加的。如果出于任何原因仍在使用旧版本,则可以使用较旧的
os.path.isdir(文件名)
功能。

您阅读了模块的文档了吗

查看以下两个链接:

如果路径引用现有路径,则返回True

如果路径是现有目录,则返回True


使用“\”而不是“\”?os.path.isdir?可能与