2

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.")
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ptar
  • 168
  • 8

2 Answers2

4

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.")
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • `csv.writer` doesn't have `fieldnames`. That's `DictWriter`. – Mark Tolonen May 06 '20 at 16:12
  • Let me check it out. I'll revert with a response. – Ptar May 06 '20 at 16:14
  • It returns this.Traceback (most recent call last): File "D:\Python\PyQt5\Proper_1.py", line 1499, in download_results with open(path, "w", newline='') as csv_file: TypeError: expected str, bytes or os.PathLike object, not tuple – Ptar May 06 '20 at 16:28
0

This did it. I'm gratefull to the contributors

def download_results(self):
    try:
        path = QFileDialog.getSaveFileName(MainWindow, "Save results", os.getenv("HOME"), "CSV(*.csv)")
        if path != "":
            with open(path[0], "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.")
Ptar
  • 168
  • 8