Having issues trying to figure out how to parse a CSV and get it into a database from perspective using the file upload component. I have looked around most of the afternoon on the forum and can’t quite find any examples that are not people trying to parse images.
I have the above and it will print out the data in the CSV file in a string list I am assuming with the decode. What I need to do though is get the data into ‘rows’ so I can insert each row from the csv to the database. I had this working in Vision with open.file (below) but can’t seem to figure out how to migrate this to perspective.
If you want to use Python’s built-in csv module, you need to construct a file-like object to pass to the reader. Luckily, Python also predicted the idea of interpreting a string in memory as a ‘file-like’ object, so the StringIO module already exists.
What you want is probably something like this:
from StringIO import StringIO
fileContents = event.file.getString("UTF-8")
reader = csv.DictReader(StringIO(fileContents))
for row in reader:
print row
If using the parse to string method, what is the equivalent of this next function? I need the system to disregard the first row in the .csv if possible. (I would like to avoid having the user have to modify any file)
Please use preformatted code </> instead of a picture of code.
What do you think the next function is doing here? Why not just ignore the first row?
from StringIO import StringIO
import csv
fileContents = event.file.getString("UTF-8")
reader = csv.DictReader(StringIO(fileContents))
for row in reader:
if row >0:
system.perspective.print(row)
Are you ignoring the first line of data, or are you ignoring it because it’s a header line? The csv module has different readers, so it helps to know what they do.
from StringIO import StringIO
import csv
csvString = """col1, col2, col3
abc, def, ghi
jkl, mno, pqr
stu, vwx, yz"""
reader = csv.DictReader(StringIO(csvString))
print 'Using csv.DictReader()'
for row in reader:
print row
print '\nUsing csv.reader()'
reader2 = csv.reader(StringIO(csvString))
for row in reader2:
print row
I tried this code but am getting the following error:
Error running action 'component.onFileReceived' on MainPages/AccountingSettings@D/root/FlexContainer_3/FileUpload: Traceback (most recent call last): File "function:runAction", line 6, in runAction
java.lang.IllegalArgumentException: java.lang.IllegalArgumentException: Cannot create PyString with non-byte value