Search code examples
pythonpython-3.xpython-docx

Python 3: How do I save a docx file to a specific directory?


I created a script that reads information from a csv file and outputs it to a docx file. My issue is that when the docx file saves, it saves it to the same folder where my python script is located. I have a folder on my desktop, called python, within this folder is where I want to save the docx file. Below is a piece of my script where this should take place. Thanks for your help!

    customer_list = r'C:\Users\path to csv file'
    csv_file = read_emails(customer_list) #Function that turns csv into dictionary

    for customer in csv_file:
        word_template = r'C:\Users\path to word template'
        document = Document(word_template)

        customer_email = customer['email']
        customer_contact = customer['contact']

        document.add_paragraph(respond_by)
        document.add_paragraph(date_sign)

        terms = r'C:\Users\path to terms and conditions'

        with open(terms,'r') as trms:
            for line in trms:
            document.add_paragraph(line)

        filename = (customer_contact + '.docx')

        document.save(filename) #Here I want to save to a different folder

Solution

  • Rather than passing just a filename, if it doesn't already take a full path, amend the Document.save method to take a full filepath and pass that instead.

    filepath = r'C:\Users\desired path\' + filename
    document.save(filepath)