首页 > 解决方案 > How to output results from a conditional statement to a MS Word file in Python?

问题描述

I have also been updating a Word file using the Python doc-x library and building tables etc into this file. Now I would like to add the results of the IF function.

if any(df.loc[df.loc[:,'Column A'] =='Y']):
        print (df.loc[:,'Value'] + "\n Placeholder A  \nPlaceholder B\n" +  str(table))
    else:
        print (df.loc[:,'Value'] + "\n Placeholder A \nPlaceholder B \n")

Any ideas on how I can achieve this? Currently, it is only printing the desired result to the console.

I have already tried using

doc.add_paragraph()

But there is no way to add in the conditional statement through this.

标签: pythonif-statement

解决方案


你可以把python if/else内联:

new_value = df.loc[:, 'Value'] + "\n Placeholder A  \nPlaceholder B\n" + (str(table) if any(df.loc[df.loc[:, 'Column A'] == 'Y']) else '')

''所以 if/else 部分给出了一个要添加到末尾的空字符串,或者str(table)

接下来,只需添加new_value到您的文档中。


推荐阅读