How to save document with different name, if certain row contains a special character?

Viewed 63

I have a normal document.save, I am trying to create an if statement that will save as failed.docx, if this character * appears in the No column.

How can I do this?

Below is the whole code that I am working with to create the docx file.

Instead of looking for column No, it'll be best to see if * is inside row[2]. Basically because anything in there will be classed as a 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")

Heres where I got up to, but defintely not the correct way of doing it:

   if "*" in cells[2]:
       print("true")
       #do not save as document.save("test.docx")
       #but save as document.save("Failed.docx")

UPDATE

I have got up to here:

for x in cells[2].text:
    if "*" in x:
        print("True")
    else:
        print("False")

If No has been selected then it prints out True, but if it hasn't it does not do anything, im confused why?...

2 Answers

You had it so close! add .text end of your cells[2].

This is what it should look like:

 if "*" in cells[2].text:
     print("true")
     document.save("Failed.docx")
 else:
     document.save("test.docx")

I may not be understanding the question. Are you asking how to change the document name, or how to properly check for the "*" character?

Changing the name is simple; just use a variable.

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)
Related