0

I need to display specific rows from multiple CSV files in a table view. For example, I want to display every 5th row from all the selected CSV files. However, I am not able to do this with the current code. Can you please help me modify it to achieve this functionality?

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import csv

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("CSV File Reader")
        self.setGeometry(100, 100, 800, 600)
        self.table = QTableWidget()
        self.setCentralWidget(self.table)
        self.csv_files = []
        self.initUI()

    def initUI(self):
        open_action = QAction("Open", self)
        open_action.setShortcut("Ctrl+O")
        open_action.triggered.connect(self.open_csv_files)
        self.menuBar().addAction(open_action)

        select_row_action = QAction("Select Row", self)
        select_row_action.triggered.connect(self.select_row)
        self.menuBar().addAction(select_row_action)

    def open_csv_files(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        files, _ = QFileDialog.getOpenFileNames(self, "Select CSV files", "", "CSV Files (*.csv);;All Files (*)", options=options)
        if files:
            self.csv_files = files
            self.table.setRowCount(0)
            self.table.setColumnCount(0)
            for file in files:
                with open(file, newline="") as f:
                    reader = csv.reader(f)
                    for row in reader:
                        self.table.insertRow(self.table.rowCount())
                        for col, cell in enumerate(row):
                            if self.table.columnCount() <= col:
                                self.table.insertColumn(col)
                            self.table.setItem(self.table.rowCount()-1, col, QTableWidgetItem(cell))

    def select_row(self):
        row, ok = QInputDialog.getInt(self, "Select Row", "Enter the row number:", min=0)
        if ok:
            self.table.setRangeSelected(QTableWidgetSelectionRange(row, 0, row, self.table.columnCount()-1), True)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
raja
  • 123
  • 7

0 Answers0