dpalm
dpalm

Reputation: 143

Read Textfile Write new CSV file

Currently I have the following code which prints my desired lines from a .KAP file.

f = open('120301.KAP')
for line in f:
    if line.startswith('PLY'):
       print line

This results in the following output

PLY/1,48.107478621032,-69.733975000000

PLY/2,48.163516399836,-70.032838888053

PLY/3,48.270000002883,-70.032838888053

PLY/4,48.270000002883,-69.712824977522

PLY/5,48.192379262383,-69.711801581207

PLY/6,48.191666671083,-69.532840015422

PLY/7,48.033358898628,-69.532840015422

PLY/8,48.033359033880,-69.733975000000

PLY/9,48.107478621032,-69.733975000000

My goal is not to have it just print these lines. I'd like to have a CSV file created named 120301.csv with the coordinates in there own columns (leaving the PLY/# behind). Simple enough? I've been trying different import CSV functions for awhile now. I can't seem to get anywhere.

Upvotes: 0

Views: 69

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

Step by step, since it looks like you're struggling with some basics:

f_in = open("120301.KAP")
f_out = open("outfile.csv", "w")

for line in f_in:
    if line.startswith("PLY"):  # copy this line to the new file
        # split it into columns, ignoring the first one ("PLY/x")
        _, col1, col2 = line.split(",")
        # format your output
        outstring = col1 + "," + col2 + "\n"
        # and write it out
        f_out.write(outstring)

f_in.close()
f_out.close()  # really bad practice, but I'll get to that

Of course this is really not the best way to do this. There's a reason we have things like the csv module.

import csv

with open("120301.KAP") as inf, open("outfile.csv", "wb") as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for row in reader:
        # if the first cell of row starts with "PLY"...
        if row[0].startswith("PLY"):
            # write out the row, ignoring the first column
            writer.writerow(row[1:])
# opening the files using the "with" context managers means you don't have
# to remember to close them when you're done with them.

Upvotes: 2

Related Questions