IAM

OPENSOURCEFAN STUDYING
STUDYINGCOMPUTERSCIENCEANDMATH COMPUTERSCIENCE

Check out the latest superpixel benchmark — Superpixel Benchmark (2016) — and let me know your opinion! @david_stutz
13thFEBRUARY2017

SNIPPET

Naive implementation of reading and writing CSV files in Python.

main.cpp
"""
Simple methods to read and write CSV.
"""

import csv
import numpy

def csv_read(csv_file, delimiter = ','):
    """
    Read a CSV file into a numpy.ndarray assuming that each row has the same
    number as columns.
    
    :param csv_file: path to CSV file
    :type csv_file: string
    :param delimiter: delimiter between cells
    :type delimiter: string
    :return: CSV contents as Numpy array as float
    :rtype: numpy.ndarray
    """
    
    cols = -1
    array = []
    
    with open(csv_file) as f:
        for cells in csv.reader(f, delimiter = delimiter):
                cells = [cell.strip() for cell in cells if len(cell.strip()) > 0]
                
                if len(cells) > 0:
                    if cols < 0:
                        cols = len(cells)
                    
                    assert cols == len(cells), "CSV file does not contain a consistent number of columns"
                    
                    cells = [float(cell) for cell in cells]
                    array.append(cells)
    
    return numpy.array(array)

def csv_write(array, csv_file, delimiter = ','):
    """
    Write a numpy array as CSV file.
    
    :param array: the array to write
    :type array: numpy.ndarray
    :param csv_file: path to CSV file
    :type csv_file: string
    :param delimiter: delimiter between cells
    :type delimiter: string
    """
    
    with open(csv_file, 'w') as f:
        for i in range(array.shape[0]):
            for j in range(array.shape[1]):
                if j < array.shape[1] - 1:
                    f.write(str(array[i, j]) + delimiter)
                else:
                    f.write(str(array[i, j]) + '\n')

What is your opinion on the code snippet? Is it working? Let me know your thoughts in the comments below or using the following platforms: