20

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.

3
  • A good question will have a sample code and any errors you get when trying to run the code.
    – sachleen
    Apr 11, 2013 at 18:38
  • 6
    @jwodder: Whatever the reason, it seems to have worked: this question got two valid answers, while the other one got none and was auto-deleted. Voting to reopen, despite the awful score. Sep 15, 2014 at 17:04
  • I am so pleased that the attempt to close this question failed on the second attempt! Dec 7, 2020 at 11:06

4 Answers 4

42

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']
1
  • 2
    I am thankful for the proposed solution but I ran into some minor problems. The error "iterator should return strings, not bytes (did you open the file in text mode?)" was solved by adding encoding='utf-8' to the open() statement.The second problem was solved using mode='r' instead of mode='rb' as given in the solution. Dec 7, 2020 at 11:28
22

Use Pandas:

import pandas as pd

pd.read_csv(filename, sep="|")

This will store the file in a dataframe. For each column, you can apply conditions to select the required values to print. It takes a very short time to execute. I tried with 111,047 rows.

1
  • Perhaps extend the sample code to extract individual values? Mar 7, 2022 at 18:52
20

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.

4
  • i have used the split string method, but it only prints "n" from the the first split column(name).
    – John Doe
    Apr 11, 2013 at 18:47
  • If you literally copy and paste my code into a text file and run it, you will see that it works. Perhaps you could share some of your code so we can see what's going wrong?
    – OdinX
    Apr 11, 2013 at 19:10
  • with open("abc.txt","r" ) as infile: data = infile.read() fields = data.split('|') print(data[0])
    – John Doe
    Apr 11, 2013 at 19:39
  • 2
    This method won't work if one of the fields has a pipe in it. Using the actual CSV library will manage that much better. May 17, 2019 at 22:11
1

In 2022, with Python 3.8 or above, you can simply do:

import csv

with open(file_path, "r") as csvfile:
    reader = csv.reader(csvfile, delimiter='|')
    for row in reader:
        print(row[0], row[1])
3
  • With a valid input file, this results in "NameError: name 'csv' is not defined". Can you make it self-contained? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today. See e.g. this, this, and this post.) Mar 7, 2022 at 18:48
  • And perhaps extend the sample code to extract some column values? Mar 7, 2022 at 18:53
  • You just need to import the csv module. I have added that. For columns, row[0], row[1], .. should give you the first and second column, and so on
    – Alexis
    Mar 11, 2022 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.