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 13, 2018 in Python by 93.lynn
• 1,590 points
110 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 13, 2018 by anto.trigg4
• 3,420 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 in Python by Omkar
• 68,480 points
45 views
0 votes
1 answer

Open a file if it exists or create and open it does not exists - Python

You can use this: f = open("ex.txt","w+") Here the ...READ MORE

answered Jun 20 in Python by Jason
37 views
0 votes
1 answer

What is the python logic to check if a number is armstrong number or not?

number = int(input("enter a number")) s = 0 temp ...READ MORE

answered Jul 30 in Python by Mohammad
• 3,170 points
40 views
0 votes
0 answers

What is the logic to check if a number is prime or not in python?

I am looking for a function with ...READ MORE

Aug 2 in Python by Waseem
• 4,480 points
32 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 424 views
+4 votes
6 answers
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
137 views
+2 votes
3 answers

what is the practical use of polymorphism in Python?

Polymorphism is the ability to present the ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
1,741 views