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
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)):
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With