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 181 views
1 answer 194 views
1 answer 165 views
1 answer 152 views
2 answers 185 views
...