Tags
python
Asked 2 years ago
16 Aug 2021
Views 2682
Frederik

Frederik posted

How do I check if multiple files exist in Python?

How do I check if multiple files exist in Python?
shyam

shyam
answered Aug 16 '21 00:00

exists() method is used to check one file exist in Python.
exists() method return True if file exist or False
we use for loop to iterate through all multiple files to check every file exist or not

Following code usefull to check if multiple files exist in Python :

from pathlib import Path 
paths =('1.txt','2.txt')
for path in paths :
	p = Path(path)
	if p.exists() :
		print(path+' exists')


you can use list or dict instead of tuple also.
fatso

fatso
answered Aug 16 '21 00:00

use os.path.exists(path) method
you need to pass the path of file to os.path.exists() to check for single file , is exists or not
use for or while loop to check for one by one file by os.path.exists() .
and import os to avoid error : name 'os' is not defined



import os
paths =['javaconvertor.py','test.py','folder name']
for path in paths :
	if os.path.exists(path)==True :
		 #do code here
Post Answer