Check whether the file exists or not

+1 vote
Without using the try statement, how can I see whether my file exists or not?
Apr 14, 2018 in Python by 93.lynn
• 1,600 points
1,751 views

5 answers to this question.

+1 vote

Simply import the "os" module and using the "exists" function, it will return a boolean value as True/ False. Write the below command:

print(os.path.exists("path"))

You can also check whether the desired path is a directory or a file. For that, use the below command:

print(os.path.isdir("path"))
answered Apr 14, 2018 by anto.trigg4
• 3,440 points
+1 vote

you can use os.path.isfile

answered Oct 18, 2018 by abc
+1 vote

You have the os.path.exists function:

import os.path
os.path.exists(file_path)

This returns True for both files and directories but you can instead use

os.path.isfile(file_name)

to test if it's a file specifically. It follows symlinks.

answered Oct 18, 2018 by Nabarupa
+1 vote

You can use the following command to check the availability of your file

import os.path
if os.path.isfile(filepath):
answered Oct 18, 2018 by Hemanth
+1 vote

Use this

import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
answered Oct 18, 2018 by reyam

Related Questions In Python

0 votes
1 answer

How to print a message or the error if a file is not found?

To print the message that file is not ...READ MORE

answered Jan 2, 2019