Skip to main content
 首页 » 编程设计

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

2024年10月01日9dudu

我创建了一个脚本,用于从 csv 文件读取信息并将其输出到 docx 文件。我的问题是,当 docx 文件保存时,它会将其保存到我的 python 脚本所在的同一文件夹中。我的桌面上有一个名为 python 的文件夹,我想在这个文件夹中保存 docx 文件。下面是我的一段脚本,应该在其中进行。感谢您的帮助!

    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 

请您参考如下方法:

与其只传递一个文件名,如果它还没有完整路径,修改Document.save 方法以获取完整文件路径并传递它.

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