Reading CSV Files
Reading CSV Files
I am trying to read CSV file contents into the memory. Does anyone know how we can do this in the upython. There is no CSV module available in the upython.
Is there any module available for upython that can read Tab Separated Values or text files or CSV files?
The https://github.com/micropython/micropyt ... master/csv is empty
Is there any module available for upython that can read Tab Separated Values or text files or CSV files?
The https://github.com/micropython/micropyt ... master/csv is empty
Re: Reading CSV Files
Code: Select all
Data[]
i=0
with open('FileName.csv','r') as file:
for line in file:
line_Str=file.readline()
line_Str=line_Str.rstrip('\n')
line_Str=line_Str.rstrip('\r')
Data.append(line_Str.split(','))
The above code load each appends each row data into the array after stripping the '\n' and '\r' which are at the end of each line.
To get a value for a particular row and column
Code: Select all
Data[0][1]
Re: Reading CSV Files
That will work as long as you don't have fields which contain commas (and you might not - just thought I'd point that out).
Re: Reading CSV Files
Thank you for pointing out.
Right now I don't have any ",' in my data.
Also this code will work if you have a Tab Separated Value file or any file that has delimiters.
Right now I don't have any ",' in my data.
Also this code will work if you have a Tab Separated Value file or any file that has delimiters.
Re: Reading CSV Files
Code: Select all
no_Rows=0 #used to find out the number of rows in the file
with open('fileName.csv','r') as file:
for line in file:
line=line.rstrip('\n')
line=line.rstrip('\r')
CAN_Parm.append(line.split(','))
no_Rows+=1
Re: Reading CSV Files
is there a reason why there is no csv module?
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Reading CSV Files
A general solution is a little more complex as CSV files can contain quoted strings which can include arbitrary contents including nasties like quotation marks and commas.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
Re: Reading CSV Files
...and the numbers might have been written out using any locale so numbers might contain commas, dots, even spaces (especially the latter is great fun)
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Reading CSV Files
Indeed. I was lumbered with this some years ago: a simple parser grew like Topsy. Without a definitive spec it was a case of working in the dark and I was never entirely convinced that I'd covered all bases. To get back on topic, a rigorous CSV parser isn't especially 'micro'. It's probably best for people with known, simple CSV subsets to roll their own.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.