Traker Traker - 28 days ago 4x
Python Question

How can I not read the last line of a csv file if it has simply 1 column? PYTHON

I have 2 csv files with 4 columns like these.

1 3 6 8\n 1 3 7 2\n
7 9 1 3\n 9 2 4 1\n
\n 1 8 2 3\n

I only want to read rows with at least 2 columns because the row with only \n, it isnĀ“t useful.

Currently, I am reading files using this:

for line in f:
list = line.strip("\n").split(",")

But, I want that lines with only 1 column should be ignored.


You can test the truthy value of the line after stripping the whitespace character. An empty string will have a falsy value which you can avoid by processing in an if block:

for line in f:
      line = line.strip("\n")
      if line: # empty string will be falsy
           lst = line.split(",")

To read rows with two columns, you can test the length of the row after splitting:

for line in f:
      row = line.strip("\n").split()
      if len(row) >= 2:

Be careful to not use the name list in your code as this will shadow the builtin list type.