Nadim Zaidi
Nadim Zaidi

Reputation: 27

Printing selected columns from a csv file in Python

I have some code here:

with open("dsasa.csv", 'rb') as csvfile:
content = csv.reader(csvfile, delimiter='|')
for row in content:
    print row```

I would like to print columns 2, 3, 4 from the csv file in the following format:

4556 | 432432898904 | Joseph Henry
4544 | 54522238904 | Mark Mulligan

I have two issues which I am encountering. One is that the delimiter pipe (|) is not appearing between the columns. The second issue is that I cannot print the specific columns I want by doing the manual way, ie. print row[2], row[3], row[4]

I looked at online info and tried a few different solutions but I can't seem to find the route to get this to work.

Any help would be greatly appreciated.

Thanks!

Upvotes: 1

Views: 4434

Answers (2)

jprockbelly
jprockbelly

Reputation: 1607

Try this:

with open("dsasa.csv", 'rb') as csvfile:
    content = csv.reader(csvfile)
    for row in content:
        print "|".join([row[2],row[3],row[4]])

The delimiter argument within csv.reader refers to the input file not the output.

Upvotes: 3

What does appear between the columns as the delimiter? Are you sure it is '|' and not a comma? I am guessing because you do not have the correct delimiter you cannot use print row[2], row[3], row[4]. Can you post a line of the CSV?

Upvotes: 0

Related Questions