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 188 views
1 answer 198 views
1 answer 170 views
1 answer 158 views
2 answers 193 views
...