有没有办法检查 .docx 文件是否存在于与 .py 文件相同的文件夹中,而不管文件路径如何?

Is there a way to check if a .docx file exists in the same folder as the .py file irrespective of filepath?

我正在尝试创建一个函数来检查特定的 docx 文件是否存在,如果不存在则创建该文件。我如何设置它以便程序检查 .py 文件所在的文件。

#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")

预期的结果是创建文件,仅当不存在于与 .py 文件相同的文件夹中时。

实际结果是函数一直在执行,因为文件路径设置不正确。

您可以从__file__变量中获取当前py文件的路径。

从那里,找到目录 os.path.dirname

然后,将其与您要搜索的文件名连接起来:

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

为了更安全,将路径转换为绝对路径(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")

然后,到处使用它,例如:

os.path.exists(path_to_docx)

doc.save(path_to_docx)