Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a file exists in python? [duplicate]

Tags:

python

excel

I am trying to make a python script to make entries in an excel file that will have daily entries. I want to check if a file exists then open it. if the file does not exist then I want to make a new file.

if have used os path exists to see if the file is present

     workbook_status = os.path.exists("/log/"+workbookname+".xlxs")
     if  workbook_status = "True":
     # i want to open the file
     Else:
     #i want to create a new file
like image 949
George Jose Avatar asked Sep 20 '25 05:09

George Jose


2 Answers

I think you just need that

try:
    f = open('myfile.xlxs')
    f.close()
except FileNotFoundError:
    print('File does not exist')

If you want to check with if-else than go for this:

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

OR

if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
like image 144
Pardeep Avatar answered Sep 21 '25 21:09

Pardeep


import os
import os.path

PATH='./file.txt'

if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print "File exists and is readable/there"
else:
    f = open('myfile.txt')
    f.close()
like image 36
艾瑪艾瑪艾瑪 Avatar answered Sep 21 '25 20:09

艾瑪艾瑪艾瑪