Hi guys,
I have a program where I need to load csv files. I have the problem where some loaded csv files have a comma as delimiter and other csv files have semicolon delimiters. For the functionality of the bigger program I want to use the load function and when a csv file has a comma as delimiter I want the function to replace the comma's by semicolons.
Basically I want to load a file, check if there are comma's and replace them for semicolon's and let the load function continue so that no matter what delimiter is used when making the csv file, my program allways 'see's' the csv file with semicolon delimiters.
Any idea's on how I can do that?
Here's my code:
import csv
import string
class Grid(object):
def __init__(self, width, height):
self.grid = []
self.array = []
self.width = width
self.height = height
self.length = width * height
for x in range(self.width):
col = []
for y in range(self.height):
cell = Cell(x, y, self)
col.append(cell)
self.array.append(cell)
self.grid.append(col)
def __getitem__(self, key):
if hasattr(key, '__len__'):
return self.grid[key[0]][key[1]]
else:
return self.array[key]
def __len__(self):
return len(self.array)
def load(cls, filename):
loadGrid = []
file = open(filename)
for line in file:
countChar = string.count(line, ',')
print countChar
if countChar > 0:
newline = line.replace(',', ';')
print newline
reader = csv.reader(open(filename), delimiter=';')
for line in reader:
loadGrid.append(line)
width = len(loadGrid[0])
height = len(loadGrid)
grid = Grid(width, height)
for x in range(width):
for y in range(height):
grid[x, y].value = loadGrid[y][x]
return grid
load = classmethod(load)
def printGrid(self):
for y in range(len(self.grid[0])):
for x in range(len(self.grid)):
print self.grid[x][y].value,
print
class Cell(object):
def __init__(self, x, y, grid):
self.x = x
self.y = y
self.grid = grid
self.value = 0
self.clusterId = -1
def setClusterId(self, clusterId):
self.clusterId = clusterId
def getClusterId(self):
return self.clusterId
target = Grid.load('csv_test_comma.csv')