Search code examples
pythonpython-docx

Is there any way to save generated word document under specific directory


I'm creating a project that allows me to save my generated word document under specific directory by using the save function which save the word document in the same directory of my program and I wanna be able to save it where i want to use the saveas function instead of save function. Here is my code:

 from docx import Document
 from docx.shared import Inches
 import os




 def generate_doxClinet(CS,NS,Filiale,Statut 
 ,NRC,NNIF,NNIS,NAI,ADRD,EMAIL,Site,Num,Num2,
              EName1,F_name1,Efonction1,Emobile1,Email1,
              EName2,F_name2,Efonction2,Emobile2,Email2,
              EName3,F_name3,Efonction3,Emobile3,Email3):
document = Document()

document.add_heading(u"Fiche de Soci\xe9t\xe9  "+NS, 0)

document.add_paragraph(unicode(u"Code Soci\xe9t\xe9 :")+str(CS))
document.add_paragraph(u'Nom  Soci\xe9t\xe9:'+NS)
p = document.add_paragraph('Filiale :'+Filiale)
p = document.add_paragraph('Statut : '+Statut)
p = document.add_paragraph('NRC :'+NRC)
p = document.add_paragraph('NNIF :'+NNIF)
p = document.add_paragraph('NNIS :'+NNIS)
p = document.add_paragraph('NAI :'+NAI)

p = document.add_paragraph('Adresse :'+ADRD)
p = document.add_paragraph('EMAIL:'+EMAIL)
p = document.add_paragraph('Site :'+Site)
p = document.add_paragraph(u'Num\xe9ro1 : '+Num)
p = document.add_paragraph(u'Num\xe9ro2:'+Num2)

p = document.add_paragraph('Nom de contact(1):'+EName1)
p = document.add_paragraph(u'pr\xe9nom de contact(1) :'+F_name1)
p = document.add_paragraph('fonction de contact(1) :'+Efonction1)
p = document.add_paragraph(u'n\xe9muro de t\xe9l\xe9phone de cantact(1) :'+Emobile1)
p = document.add_paragraph('email de contact(1):'+Email1)

p = document.add_paragraph('Nom de contact(2):'+EName2)
p = document.add_paragraph(u'pr\xe9nom de contact(2) :'+F_name2)
p = document.add_paragraph('fonction de contact(2) :'+Efonction2)
p = document.add_paragraph(u'n\xe9muro de t\xe9l\xe9phone de cantact(2) :'+Emobile2)
p = document.add_paragraph('email de contact(2):'+Email2)

p = document.add_paragraph('Nom de contact(3):'+EName3)
p = document.add_paragraph(u'pr\xe9nom de contact(3) :'+F_name3)
p = document.add_paragraph('fonction de contact(3) :'+Efonction3)
p = document.add_paragraph(u'n\xe9muro de t\xe9l\xe9phone de cantact(3) :'+str(Emobile3))
p = document.add_paragraph('email de contact(3):'+Email3)

document.save('Clinet'+str(CS)+'.docx')

Solution

  • The save method takes a file path. At the moment you just pass it the file name but you could pass it the absolute directory where you wish the file to be saved. For example

    document.save('C:\Users\Me\Documents\{0}.docx'.format(CS))
    

    If you need to do complex file path manipulation like joining paths together, remember to use os.path.