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

Time:04-12

i want to build a function that convert names from csv to a document in word by docx library and i want to create an empty file with os.makedirs(), the file is created but i cant get its path to later join path with word document to save the document in that file here is my code:

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

CodePudding user response:

If I'm understanding what you're trying to accomplish, then just use the path variable you made earlier. Since you used os.makedirs(path), then the path to that would just be the path object.

CodePudding user response:

If you don't change the location, you can use the same path. If you change the location, you can get the path from your script using os.getcwd() and join it wiht the path using os.path.join()

You can store the result of os.path.join(os.getcwd(), path) to a variable and use it later. You can compose that absolute path before creating the file, so you'll have the entire path

  • Related