4

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
2
  • So what's missing from your current code is writing to an existing or new file? What's wrong with your current code? Commented Aug 6, 2019 at 12:15
  • yes, writing to existing file. i want to know if the load_workbook() will overwrite the existing file or it will just open it and then i can append to the existing file Commented Aug 6, 2019 at 12:18

3 Answers 3

18

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)):
Sign up to request clarification or add additional context in comments.

Comments

4
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()

Comments

1

You should use following statement:

if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
    #  Open file 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.