user1615275
user1615275

Reputation:

read | deliminator file and extract variable in Python

I am trying to read in a txt file with deliminator "|", and then extract the second and third variable. so the data looks like this:

a|bb|cc|   
aaa|b|cccc|

and I want to create a data with only the second and third variable:

bb  cc
b cccc

any suggestions?

Thank you!

Upvotes: 0

Views: 161

Answers (4)

Levon
Levon

Reputation: 143047

with open("data.txt") as f:
    for line in f:
        col2, col3 = line.split('|')[1:3] # get 2nd and 3rd column
        print col2, col3 # this could be written to a file if needed

will give you

bb cc 
b cccc

where data.txt is your data file.

Explanation:

You read the file, line-by-line, split each line with the | delimiter, and print the 2nd and 3rd element on each line. This data could also be written to a file, or manipulated further.

Upvotes: 2

chucksmash
chucksmash

Reputation: 5997

Use the csv module

import csv
input = csv.reader(open('your_file.txt', 'rb'),delimiter="|")
for row in input:
    print row[1:]

This will print out each of the other values in each row aside from the first one. You would of course do whatever processing you wanted to do instead where I've printed.

Upvotes: 2

varunl
varunl

Reputation: 20229

You can use the csv module. Simple and elegant.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

Use the csv module with an appropriate dialect, then slice the resultant list per line and output it.

Upvotes: 0

Related Questions