2016-08-08 7 views
0

現在、私は.KAPファイルから必要な行を印刷する次のコードを持っています。テキストファイルを読む新しいCSVファイルを書き込む

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関数を試してきました。私はどこにもいられないようだ。ステップバイ

+0

具体的に何を試しましたか?何が問題になりましたか? – Harrison

+1

'csv'モジュールを' open() '、' write() '、' close() 'と一緒に使いたいのですか? –

+0

のいずれか、または結果が十分なCSVファイルを提供している限り。私は私の試みでは、csvモジュールを手に取っています。 – dpalm

答えて

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. 
+0

@dpalm最初のスクリプトではおそらくファイルを閉じるのを忘れていました。 2番目のスクリプト私は '行'を '行'に変更してより記述的にし、 'line [0] .startswith'を忘れました。一定。 –

+1

うん、あなたはそれを理解できると確信しています!がんばろう –

関連する問題