Reputation:
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.
Upvotes: 0
Views: 1272
Reputation: 895
If they are legitimately comma-separated csv files, try the csv module. You will still have to eliminate empty rows, as in the other answers. For this, you can test for an empty list (which is a falsey value when evaluated as an expression in an if statement).
import csv
with open('filename.csv' as f):
reader = csv.reader(f)
rows = [row for row in reader if row]
rows
now contains all non-empty rows in the csv file.
Upvotes: 1
Reputation: 4422
You can just quit the loop when you hit the blank line.
if not line.strip():
break
Upvotes: 1
Reputation: 78556
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.
Upvotes: 0