我想建立一个函数,通过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
对象。
如果不更改位置,可以使用相同的path
。如果更改位置,则可以使用os.getcwd()
从脚本中获取路径,并使用os.path.join()
将其与path
连接
您可以将os.path.join(os.getcwd(), path)
的结果存储到一个变量中,然后再使用它。你可以在创建文件之前组成这个绝对路径,这样你就有了整个路径