0

I am trying to create a function that checks to see if a specific docx file exists and then create the file if it doesn't exist. How do I et this up so that the program checks the file in which the .py file is in.

#Creating The Finance Log Word Doc
#If the file does not exist create file
if os.path.exists("Finance Log.docx")==False:
    doc = docx.Document()
    run = doc.add_paragraph().add_run()
    # Apply Style
    Tstyle = doc.styles['Normal']
    font = Tstyle.font
    font.name = "Nunito Sans"
    font.size = Pt(48)
    Title = doc.add_paragraph()
    TRun = Title.add_run("Finance Log")
    TRun.bold = True
    doc.add_picture('Scouts_Logo_Stack_Black.png', width=Inches(4.0))
    doc.save("Finance Log.docx")

The expected result is that the file is created, only when absent from the same folder as the .py file.

The actual results is that the function keeps executing, since the filepath is not set up correctly.

martineau
  • 119,623
  • 25
  • 170
  • 301
Lyra Orwell
  • 1,048
  • 4
  • 17
  • 46

1 Answers1

1

You can get the path to the current py file from the __file__ variable.

From that, find the directory as os.path.dirname.

Then, join that with the filename that you are searching for:

my_directory = os.path.dirname(__file__)
path_to_docx = os.path.join(my_directory, "Finance Log.docx")

To be safer, convert the path to absolute path (because it sometimes isn't):

my_directory = os.path.abspath(os.path.dirname(__file__))
path_to_docx = os.path.join(my_directory, "Finance Log.docx")

Then, use that everywhere, e.g.:

os.path.exists(path_to_docx)

doc.save(path_to_docx)
zvone
  • 18,045
  • 3
  • 49
  • 77