Python Forum

Full Version: Deleting rows based on cell value in Excel
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
PyCharm does not change how Python programs work. The program contains an error. It will run fine for some worksheets and crashes on others. This is the error:
if 'X' in row[1].value or 'x' in row[1].value:
If row[1] is an int (or other non-iterable), this will raise an error.
Error:
TypeError: argument of type 'int' is not iterable
Your program should check the cell value type before treating it like a string.
import openpyxl

def remove_x(src_file, dst_file):
    """Removes rows that contain X or x"""
    workbook = openpyxl.load_workbook(src_file)
    for sheet in workbook:
        for row in sheet.iter_rows():
            for cell in row:
                value = cell.value
                if isinstance(value, str) and "x" in value.lower():
                    sheet.delete_rows(cell.row)
                    break
    workbook.save(dst_file)

remove_x("data.xlsx", "modified.xlsx")
Thanks will have another play based on your reply.
Pages: 1 2