[Tutor] CSV Read
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Jun 29 18:25:13 EDT 2018
On 29/06/18 13:18, Sergio Rojas wrote:
> # read the whole file
> with open(thefilename, 'r') as theFile:
>>>> contentfile = theFile.read()
>
> # split the file in lines according to the newline character "\n"
> templines = []
> for line in contentfile.splitlines():
>>>>> templines.append(line.strip())
>
> #Following the pattern extract the data
> thelines = []
> for line in templines:
You might as well just use readlines()...
Or better still use for on the file itself:
with open(thefilename, 'r') as theFile
for line in theFile:
....
>>>> if ':' in line:
>>>>>>> temp = line.split(":")
>>>>>>> for i in range(len(temp)):
>>>>>>>>> try:
>>>>>>>>>>>>> temp[i] = float(temp[i])
>>>>>>>>> except:
>>>>>>>>>>>>> temp[i] = temp[i]
def makeFloats(sep, line):
temp = line/split(sep)
for i,v in enumerate(temp)
try:
temp[i] = float(v)
except ValueError,TypeError: pass
return temp
if ':' in line: line = makeFloats(':', line)
if(',' in line: line = makeFloats(',', line)
# into pandas next...
Although I'm not totally sure that is what the OP wanted.
What happens about the header lines for example?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list