简体   繁体   中英

How can I not read the last line of a csv file if it has simply 1 column in 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.

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.

You can just quit the loop when you hit the blank line.

if not line.strip():
    break

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM