0

I have a CSV file, /home/user/file.csv, such as:

V1
1.24
4.55
3

I am trying to read in only the numbers, without the prior knowledge that there is a header.

How do I read this and skip all String elements keeping only ints/floats/long/etc?

The following attempt does not work because line is not a number even if the row I am reading is a number:

f_in = open('/home/user/file.csv')
for line in f_in:
    if !isinstance(line,basestring):
        #Now we only have the rows that are numbers (but not really!)
user2763361
  • 3,789
  • 11
  • 45
  • 81

3 Answers3

3
try:
    float(line)
except ValueError:
    # not a number

also see "Ask forgiveness not permission" - explain

EDIT: as per OP request, a row that looks like:

1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,1,0,0,1

import csv
with open('/home/user/file.csv') as csvfile:
    for row in csv.reader(csvfile):
        for n in row:
            try:
                float(line)
            except ValueError:
                # not a number
Community
  • 1
  • 1
Guy Gavriely
  • 11,228
  • 6
  • 27
  • 42
1
f_in = [1.24, 4.55, 3, "aaa"]

for line in f_in:
    try:
        float(line)
        #it is number
    except ValueError:
        #it isn't a number
michalczukm
  • 9,963
  • 6
  • 40
  • 47
1

The csv module provides a Sniffer class that will figure out if your file has a (one-line) header.

has_header(sample)

Analyze the sample text (presumed to be in CSV format) and return True if the first row appears to be a series of column headers.

roippi
  • 25,533
  • 4
  • 48
  • 73