C
Carlos Grohmann
Hi all, I'm using csv to read text files, and its working fine, except
in two cases:
- when there is only one line of text (data) in the file
- when there is a blank line after the last data line
this is the kind of data:
45 67 89
23 45 06
12 34 67
....
and this is the function:
def getData(paths):
"""get data from file and create lists with values and column
names."""
filehandle = paths# # filehandle = os.path.join(dirname,
filename)
csvfile = open(filehandle,'r') # Open the file and read the
contents
sample = csvfile.read( 1024 )# Grab a sample
csvfile.seek( 0 )
dialect = csv.Sniffer().sniff(sample) # Check for file format with
sniffer.
csvfile = csv.reader( csvfile, dialect )
if csv.Sniffer().has_header( sample ): #if there is a header
colnames = csvfile.next() # label columns from first line
datalist = list( csvfile ) # append data to a list
else: #if there is NO header
datalist = list( csvfile ) # append data to a list
colnames = ['col_%i' % i for i in range(len(datalist[0]))] #
label columns as col_1, col_2, etc
return datalist, colnames
TIA for any help.
in two cases:
- when there is only one line of text (data) in the file
- when there is a blank line after the last data line
this is the kind of data:
45 67 89
23 45 06
12 34 67
....
and this is the function:
def getData(paths):
"""get data from file and create lists with values and column
names."""
filehandle = paths# # filehandle = os.path.join(dirname,
filename)
csvfile = open(filehandle,'r') # Open the file and read the
contents
sample = csvfile.read( 1024 )# Grab a sample
csvfile.seek( 0 )
dialect = csv.Sniffer().sniff(sample) # Check for file format with
sniffer.
csvfile = csv.reader( csvfile, dialect )
if csv.Sniffer().has_header( sample ): #if there is a header
colnames = csvfile.next() # label columns from first line
datalist = list( csvfile ) # append data to a list
else: #if there is NO header
datalist = list( csvfile ) # append data to a list
colnames = ['col_%i' % i for i in range(len(datalist[0]))] #
label columns as col_1, col_2, etc
return datalist, colnames
TIA for any help.