Tags
Asked 3 years ago
16 Aug 2021
Views 764
Patricia

Patricia posted

What method of file is used to test if a file or directory exists?

What method of file is used to test if a file or directory exists?
jaydeep

jaydeep
answered Aug 16 '21 00:00

exists() method from pathlib help to check whether file or directory exits or not.


from pathlib import Path
 if Path(path).exists() == True :
           #do something


Path('file or directory path').exists() is from the pathlib , can use to check whether file or directory exists or not.
exists() returns True if file or directory exists
exists() returns False if file or directory exists

sachin

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())
 

python

python
answered Aug 16 '21 00:00


os.path.exists(path) method is used to check file or directory exists at the given path or not.
path refers to an absolute or relative file or directory path.
need to import os module to use os.path.exists() method .

Python code to test if a file or directory exists :

import os
if  os.path.exists(path)==True :
         print("path exists ")

Post Answer