Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a pipe delimited file in python

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.

like image 588
John Doe Avatar asked Apr 11 '13 18:04

John Doe


People also ask

How do you use a pipe delimiter?

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.

Can CSV be pipe delimited?

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.

How do I save a pipe delimited file as a CSV file?

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.


2 Answers

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']
like image 176
Spencer Rathbun Avatar answered Oct 09 '22 11:10

Spencer Rathbun


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.

like image 34
vimist Avatar answered Oct 09 '22 12:10

vimist