我有一个正常的document.save
,我正在尝试创建一个if
语句,如果这个字符*
出现在No
列中,它将另存为failed.docx
。
我该怎么做?
下面是我用来创建docx
文件的完整代码。
与其寻找列No
,不如查看*
是否在row[2]
内。基本上是因为那里的任何东西都会被归类为no
.
vars = []
for idx,i in enumerate(info):
var = IntVar(value=0)
vars.append(var)
lblOption = Label(main,text=i)
btnYes = Radiobutton(main, text="Yes", variable=var, value=2)
btnNo = Radiobutton(main, text="No", variable=var, value=1)
btnNa = Radiobutton(main, text="N/A", variable=var,value=0)
lblOption.grid(column=4,row=idx, sticky = W)
btnYes.grid(column=1,row=idx)
btnNo.grid(column=2,row=idx)
btnNa.grid(column=3,row=idx)
document = Document()
#add table
table = document.add_table(1, 4)
#style table
table.style = 'Table Grid'
#populate header row
heading_cells = table.rows[0].cells
heading_cells[0].text = "Options"
heading_cells[1].text = "Yes"
heading_cells[2].text = "No"
heading_cells[3].text = "N/a"
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
elif val == 1: # checks if no
cells[2].text = "*"
elif val == 0: # checks if N/A
cells[3].text = "*"
#save doc
document.save("test.docx")
这是我开始的地方,但绝对不是正确的方法:
if "*" in cells[2]:
print("true")
#do not save as document.save("test.docx")
#but save as document.save("Failed.docx")
更新
我已经到这里了:
for x in cells[2].text:
if "*" in x:
print("True")
else:
print("False")
如果选择了No
,那么它会打印出 True,但如果没有,它不会执行任何操作,我很困惑为什么?...
你离得这么近! 添加.text
cells[2]
的结尾。
这是它应该的样子:
if "*" in cells[2].text:
print("true")
document.save("Failed.docx")
else:
document.save("test.docx")
我可能不明白这个问题。您是在问如何更改文档名称,还是如何正确检查"*"字符?
更改名称很简单;只需使用变量即可。
docname = "test.docx"
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
elif val == 1: # checks if no
cells[2].text = "*"
docname = "failed.docx"
elif val == 0: # checks if N/A
cells[3].text = "*"
docname = "failed.docx"
document.save(docname)