newbe help
Jeff Sandys
sandysj at asme.org
Fri Oct 20 13:58:46 EDT 2000
How I read a comma separated values file (*.csv)
#====================== start of code
import string
def trimcr(str):
if str == '':
return ''
if str[-1:] in '\n\r':
return trimcr(str[:-1])
else:
return str
#====================================
class ssrw:
def __init__(self):
#---instance variables---
self.rcdata = []
self.delim = ","
# change to "\t" for tab delimited files
#===methods==========================
def read(self,file):
"reads a file into 'rcdata' parsed by 'delim' string"
s = open(file, 'r')
r = trimcr(s.readline())
while r <> '':
self.rcdata.append(string.split(r, self.delim))
r = trimcr(s.readline())
s.close()
#
#======================== end of code
How to use
>>> z = ssrw()
>>> z.read("my.csv")
>>> row1col1 = z.rcdata[1][1]
>>> row1col2 = z.rcdata[1][2]
>>> row2col1 = z.rcdata[2][1]
Thanks,
Jeff Sandys
Xander van Es wrote:
>
> Hi all,
>
> I was wondering if it is possible to assign values from a comma seperated
> file to diferent variables.
> so between 2 values there is a comma, and i want to assign those two values
> to two different variables.
> is there a way i can do that in python??
>
> Xander
More information about the Python-list
mailing list