读取文本文件编写新的CSV文件

时间:2016-08-08 19:37:35

标签: python csv

目前我有以下代码从.KAP文件打印我想要的行。

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

这会产生以下输出

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

我的目标不是只打印这些线条。我想创建一个名为120301.csv的CSV文件,其坐标位于自己的列中(将PLY /#留在后面)。够简单吗?我现在已经尝试了不同的导入CSV功能。我似乎无法到达任何地方。

1 个答案:

答案 0 :(得分:2)

一步一步,因为看起来你正在努力解决一些基础问题:

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

当然,这不是最好的方法。我们有csv模块之类的原因。

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.