-1

This is probably a pretty trivial problem, but here goes -- I have been given a plaintext list of addresses in this format:

Name1 ¶
Address1 ¶
City1, State1, Zip1 ¶

Name2 ¶
Address2 ¶
City2, State2, Zip2 ¶

... and so on. My job is to mail merge these into labels for envelopes. However, MS Office's mail merge function needs for the list of addresses to be a comma-separated list; it can't seem to distinguish between addresses in the format I was given. I can't figure out a way to convert this plaintext list to a comma-separated list. Would anyone know how to do this via MS Office, a Python script, etc...?

Thank you in advance!!

Evan
  • 13
  • 2
  • when you say, '¶', do you mean that symbol is literally present in your text file? Or do you mean for ¶ to represent something else? – Robᵩ Sep 02 '15 at 16:39
  • Ah, sorry, the ¶ represents a paragraph break (the person inputting the data pressing ENTER) – Evan Sep 02 '15 at 16:40

1 Answers1

0

This script will read text on its standard input in the form you gave, and write text to its standard output as a CSV, with one row per input paragraph, one column per input line.

Use it like so: python para2csv.py < inputfile.txt > outputfile.csv

#!/usr/bin/python2.7

# Copy the input stream to the output stream, converting
# paragraphs into CSV rows.

import csv
import sys

def para(f):
    row = []
    for line in f:
        line = line.strip()
        if line:
            row.append(line)
        elif row:
            yield row
            row = []
    if row:
        yield row

writer = csv.writer(sys.stdout)
for row in para(sys.stdin):
    writer.writerow(row)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thank you very much for that. I am still very new to Python and can't figure out how to run it now. Could someone give me some quick instructions on what to do with this very nice script? Thanks!!!!!! – Evan Sep 02 '15 at 17:19