[SOLVED] How to import a CSV file with a unique delimiter character

Good afternoon,

I have a CSV file delimited with a pipe | character. How would I go about importing this into a powertable?
Currently this code below works for a comma delimited CSV file:

import csv

path = system.file.openFile("csv")
csvData = csv.reader(open(path)) 
	
header = csvData.next()
data = system.dataset.toDataSet(header, list(csvData))

return data

I just use .split on the line and then parse it that way.

import os.path
path = system.file.openFile("csv")
myfile = open(path, "r")
for line in myfile:
    sline = line.split('|')
    var1 = sline[1]
    var2 = sline[2]

etc.

1 Like

You beat me to a solution… I googled this moments after posting lol.

https://docs.python.org/3/library/csv.html#csv-fmt-params

import csv
	
path = system.file.openFile("csv")
csvData = csv.reader(open(path), delimiter='|') 
	
header = csvData.next()
data = system.dataset.toDataSet(header, list(csvData))

return data

Just be aware that the ‘naive’ split() solution will fail if you have something like this:
"row"|"a weird row containing | the delimiter"|"another row"
Adjusting the csv reader is probably ‘safer’ for potential malformed input like that (if it’s a risk).

3 Likes

We have homegrown text files from a previous HMI system that are | delimited and consistent.
:slight_smile:

1 Like