sachin
answered Aug 16 '21 00:00
to check wheather directory exists or not in Python
in Python , we use is_dir() method to check whether given directory or folder exists or not
is_dir() method returns True if directory exits
is_dir() method returns False if directory does not exits
1. import needed packages which is Path from pathlib
from pathlib import Path
2. assign the absolute or relative path of directory or folder to Path object
p = Path('absolute or relative path of folder or directory')
3. use is_dir to find out given folder or directory exists or not
p.is_dir()
Final code is below for to test if a directory exists in Python :
from pathlib import Path
path ='folder path'
p = Path(path)
print(p.is_dir())
Result can be True or False
to check wheather file exists or not in Python
in Python , we use is_file() method to check whether given file exists or not
is_file() method returns True if file exits
is_file() method returns False if file does not exits
1. import needed packages which is Path from pathlib
from pathlib import Path
2. assign the absolute or relative path of directory or folder to Path object
p = Path('absolute or relative path of file')
3. use is_file to find out given file exists or not
p.is_file()
Final code is below for to test if a file exists in Python :
from pathlib import Path
path ='file complete or relative path'
p = Path(path)
print(p.is_file())