Tristan Forward
Tristan Forward

Reputation: 3514

String to Csv file using Python

I have the following string

string = "OGC Number | LT No | Job /n 9625878 | EPP3234 | 1206545/n" and continues on  

I am trying to write it to a .CSV file where it will look like this:

OGC Number | LT No | Job   
------------------------------
9625878   | EPP3234  | 1206545
9708562   | PGP43221 | 1105482
9887954   | BCP5466  | 1025454

I am having trouble getting the formatting.

I think I need to use:

string.split('/n')
string.split('|')

Thanks.

Windows 7, Python 2.6

Upvotes: 1

Views: 492

Answers (3)

Peter Vierstrom
Peter Vierstrom

Reputation: 11

EDIT: Oops, I missunderstood your question!

The code below will use two regular expressions to do the modifications.

import re

str="""OGC Number | LT No | Job   
------------------------------
9625878   | EPP3234  | 1206545
9708562   | PGP43221 | 1105482
9887954   | BCP5466  | 1025454
"""
# just setup above 

# remove all lines with at least 4 dashes
str=re.sub( r'----+\n', '', str )

# replace all pipe symbols with their 
# surrounding spaces by single semicolons
str=re.sub( r' +\| +', ';', str )

print str

Upvotes: 0

anijhaw
anijhaw

Reputation: 9402

If you are interested in using a third party module. Prettytable is very useful and has a nice set of features to deal with and print tabular data.

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142156

Untested:

text="""
OGC Number | LT No | Job   
------------------------------
9625878   | EPP3234  | 1206545
9708562   | PGP43221 | 1105482
9887954   | BCP5466  | 1025454"""

import csv
lines = text.splitlines()
with open('outputfile.csv', 'wb') as fout:
    csvout = csv.writer(fout)
    csvout.writerow(lines[0]) # header
    for row in lines[2:]: # content
        csvout.writerow([col.strip() for col in row.split('|')])

Upvotes: 1

Related Questions