Search code examples
pythonpython-3.xcsvpyqt5qtablewidget

Missing column headers in saved file


Is it possible I get assistance here? My function saves a file with a space after every row, also the column headers are not saved. Here is the function.

def download_results(self):
    try:
        path = QFileDialog.getSaveFileName(MainWindow, 'Save results', os.getenv('HOME'), 'CSV(*.csv)')
        if path[0] != '':
            with open(path[0], 'w') as csv_file:
                writer = csv.writer (csv_file, dialect = 'excel', delimiter = ',')
                for row in range(self.analysis_table.rowCount()):
                    row_data = []
                    for column in range(self.analysis_table.columnCount()):
                        item = self.analysis_table.item(row, column)
                        if item is not None:
                            row_data.append(item.text())
                        else:
                            row_data.append('')
                    writer.writerow(row_data)
        QMessageBox.information(MainWindow,"Success","Succeeded")
    except:
        QMessageBox.warning(MainWindow,"Failed","Operation failed.")

Solution

  • You have to extract the text from the QTableWidgetItem using horizontalHeaderItem() method:

    def download_results(self):
        try:
            path, _ = QFileDialog.getSaveFileName(
                MainWindow, "Save results", os.getenv("HOME"), "CSV(*.csv)"
            )
            if path:
                with open(path, "w", newline='') as csv_file:
                    writer = csv.writer(csv_file)
                    headers = []
                    for c in range(self.analysis_table.columnCount()):
                        it = self.analysis_table.horizontalHeaderItem(c)
                        if it is not None:
                            headers.append(it.text())
                        else:
                            headers.append("")
                    writer.writerow(headers)
                    for row in range(self.analysis_table.rowCount()):
                        row_data = []
                        for column in range(self.analysis_table.columnCount()):
                            item = self.analysis_table.item(row, column)
                            if item is not None:
                                row_data.append(item.text())
                            else:
                                row_data.append("")
                        writer.writerow(row_data)
            QMessageBox.information(MainWindow, "Success", "Succeeded")
        except:
            QMessageBox.warning(MainWindow, "Failed", "Operation failed.")