【问题标题】:Missing column headers in saved file保存的文件中缺少列标题
【发布时间】:2020-08-21 16:04:59
【问题描述】:

我可以在这里获得帮助吗? 我的函数在每行之后保存一个带有空格的文件,也不保存列标题。 这是函数。

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.")

【问题讨论】:

  • “我的函数保存一个文件,每行后有一个空格”,见stackoverflow.com/q/3348460/235698
  • 仅供参考,dialect='excel' 是默认值,delimiter=','excel 方言的分隔符,因此两者都不是必需的。

标签: python python-3.x csv pyqt5 qtablewidget


【解决方案1】:

您必须使用horizontalHeaderItem() 方法从 QTableWidgetItem 中提取文本:

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.")

【讨论】:

  • csv.writer 没有fieldnames。那是DictWriter
  • 让我看看。我会回复回复。
  • 它返回 this.Traceback(最近一次调用最后一次):文件“D:\Python\PyQt5\Proper_1.py”,第 1499 行,在带有 open(path, "w", newline= 的 download_results 中'') as csv_file: TypeError: expected str, bytes or os.PathLike object, not tuple
【解决方案2】:

这样做了。非常感谢贡献者

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.")

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多