[Reading a csv file and removing the lines that I won't be needing]
-
Hello guys,
I hope you're doing very well.
So I tried to read a csv file by displaying it in a QTableView.
However there are some lines that I won't to delete so here is what I tried to dovoid MainWindow::on_actionOpen_triggered() { auto filename=QFileDialog::getOpenFileName(this,"Open", QDir::rootPath(), "CSV File(*.csv)"); if (filename.isEmpty()) { return; } QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return; } QTextStream xin(&file); int ix = 0; while(!xin.atEnd()) { mModel->setRowCount(ix); auto line = xin.readLine(); qDebug() << "line"<<line; auto values = line.split(";"); qDebug() << "values" << values; const int colCount = values.size(); mModel->setColumnCount(colCount); for (int jx = 0; jx< colCount; ++jx) { setValueAt(ix, jx, values.at(jx)); } qDebug() << "values at jx" << values.at(3); if (values.at(3)!='5') { mModel->removeRow(ix);} ++ix; } file.close(); }
After displaying the whole csv file, I wanted to remove all the rows where the values of the third columns are different from '5' But that didn't work.
Can someone please help me ?
Thanks. -
@appdev said in [Reading a csv file and removing the lines that I won't be needing]:
But that didn't work.
What didn't work? If you want to use
removeRow()
like you doif (values.at(3)!='5') { mModel->removeRow(ix);} ++ix;
you will not want to increment
ix
if you remove the row, put it in anelse
?Or, make your decision about looking at column #3 before you commit to to adding the row in the first place?
-
@JonB Thank your for the quick reply,
What didn't work is that when i run my application and open the csv file, I get an empty file with 9 columns since my csv file contains 9 columns.
Okay so for the first solution, you mean that I should do like this:
if (values.at(3)!='5') { mModel->removeRow(ix);} else { ++ix; }
?
I tried it but it didn't work, it looks like the program isn't taking the if condition into consideration.
I thought about the second solution you suggested but the row removal seems to be less complicated. -
@appdev
I really don't know what your issue is.if (values.at(3)!='5') { mModel->removeRow(ix);} else { ++ix; }
Yes to the
else
.You seem to me to have a logic problem with your initialisation of
int ix = 0;
followed bymModel->setRowCount(ix);
. So you set 0 rows and then callsetValueAt(0, ...)
. You need to think about what you are doing, and at a guessmModel->setRowCount(ix + 1);
.I thought about the second solution you suggested but the row removal seems to be less complicated.
If you think so, fine. Otherwise put your columns into
values
, check whethervalues.at(3)!='5'
, and only add the row with its column values after the check on that column instead of before.