How to check whether a file exists in Python

3 Answers

0 votes
import os.path

filename = "d:\data.txt"

if os.path.isfile(filename):
    print("file exist")
else:
    print("file not exist")


'''
run:

file exist

'''

 



answered Oct 22, 2017 by avibootz
0 votes
from pathlib import Path

filename = "d:\data.txt"

f = Path(filename)

if f.is_file():
    print("file exist")
else:
    print("file not exist")


'''
run:

file exist

'''

 



answered Oct 22, 2017 by avibootz
0 votes
import os.path

file = "d:\data.txt"

if os.path.exists(file):
    print("file exist")
else:
    print("file not exist")


'''
run:

file exist

'''

 



answered Oct 22, 2017 by avibootz

Related questions

1 answer 183 views
1 answer 195 views
1 answer 168 views
1 answer 155 views
2 answers 191 views
...