簡體   English   中英

我如何知道 os.makedirs() 創建的文件的路徑並將其存儲在變量中供以后使用?

[英]how can i know the path of a file created by os.makedirs() and store it in a variable for later use?

我想構建一個 function,通過 docx 庫將名稱從 csv 轉換為 word 文檔,我想使用 os.makedirs() 創建一個空文件,該文件已創建但我無法獲取其路徑以便稍后使用 word 加入路徑將文檔保存在該文件中的文檔是我的代碼:

    import docx
    import pandas as pd
    from datetime import datetime
    import os
    from docx2pdf import convert
    from pathlib import Path
def auto_fill(x,y):
    database=pd.read_csv(x)
    df=pd.DataFrame(database)
    df=df.dropna(axis=0)
    targeted_doc=docx.Document(y)
    date = datetime.date(datetime.now())

    strdate = date.strftime("%m-%d-%Y")
    path = strdate
    newfile = os.makedirs(path)
    newfile_path = path(newfile)
    for i in range(len(df.Name)+1):
        for n in range (len(targeted_doc.paragraphs)+1):
            if targeted_doc.paragraphs[n].text=="Name of trainee":
                name=targeted_doc.paragraphs[n].runs[0].text=df.at[i,'Name']

        for m in range(len(targeted_doc.paragraphs) + 1):
            if targeted_doc.paragraphs[m].text == "tissue date":
                date = targeted_doc.paragraphs[n].runs[0].text = strdate
        for l in range(len(targeted_doc.paragraphs) + 1):
            if targeted_doc.paragraphs[n].text == "tserial number":
                sr_num = targeted_doc.paragraphs[l].runs[0].text = df.at[i, 'serial number']

        name_of_file = (f"{df.at[i, 'Name']}.docx")
        outputdoc=targeted_doc.save(name_of_file)
        path_of_document=path(outputdoc)
        completesave = os.path.join(path_of_document, name_of_file)
        convert(path_of_document,newfile_path+f"{name_of_file}.pdf")

auto_fill("database.csv","01.docx")

如果我理解您要完成的任務,那么只需使用您之前創建的path變量即可。 由於您使用os.makedirs(path) ,那么它的路徑就是path object。

如果不更改位置,則可以使用相同的path 如果更改位置,則可以使用os.getcwd()從腳本中獲取路徑,並使用os.path.join() () 將其與path連接

您可以將os.path.join(os.getcwd(), path)的結果存儲到變量中並在以后使用。 您可以在創建文件之前編寫該絕對路徑,因此您將擁有整個路徑

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM