I'm trying to parse a pipe-delimited file and pass the values into a list, so that later I can print selective values from the list.
The file looks like:
name|age|address|phone|||||||||||..etc
It has more than 100 columns.
Changing the Default Delimiter in Regional Settings Change the List separator to a pipe character. The pipe character is found above the ENTER key on the keyboard (SHIFT + \). Click OK.
If your csv file consists of either pipe/comma separated data then you can go with pipe/comma as delimiter else if it a combined of comma and pipes.
Exporting Excel Files as Pipe Delimited To save the file as Delimited, you'll need to click the Office button and choose Save As –> Other Formats. Then select CSV (Comma delimited)(*. csv) from the drop-down list, and give it a name.
Use the 'csv' library.
First, register your dialect:
import csv
csv.register_dialect('piper', delimiter='|', quoting=csv.QUOTE_NONE)
Then, use your dialect on the file:
with open(myfile, "rb") as csvfile:
for row in csv.DictReader(csvfile, dialect='piper'):
print row['name']
If you're parsing a very simple file that won't contain any |
characters in the actual field values, you can use split
:
fileHandle = open('file', 'r')
for line in fileHandle:
fields = line.split('|')
print(fields[0]) # prints the first fields value
print(fields[1]) # prints the second fields value
fileHandle.close()
A more robust way to parse tabular data would be to use the csv
library as mentioned in Spencer Rathbun's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With