0

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
Pardeep
  • 2,153
  • 1
  • 17
  • 37
George Jose
  • 166
  • 1
  • 1
  • 11
  • So what's missing from your current code is writing to an existing or new file? What's wrong with your current code? – Christopher Janzon Aug 06 '19 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 – George Jose Aug 06 '19 at 12:18

3 Answers3

12

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)):
Pardeep
  • 2,153
  • 1
  • 17
  • 37
3
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()
1

You should use following statement:

if os.path.isfile("/{file}.{ext}".format(file=workbookname, ext=xlxs)):
    #  Open file 
milanbalazs
  • 4,811
  • 4
  • 23
  • 45