2016-11-19 2 views
4

KML 파일에서 좌표를 추출하는 코드가 있습니다. 그것은 아름답게 작동하고 그것이 내가 CSV 파일에 인쇄하고자하는 방식으로 화면에 인쇄합니다. 그러나 CSV 파일에 쓰기를 시도하면 결과 파일이 비어 있습니다.CSV 파일에 목록 작성하기

아래의 방법과 .write.writerows을 사용하는 표준 텍스트 출력 방법을 모두 시도했습니다. 모두 같은 결과가 있습니다. 여기

은 내가 KML 사용하고 있습니다 :

<?xml version="1.0" encoding="UTF-8"?> 
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom"> 
<Document> 
    <name>Test3.kml</name> 
    <Style id="s_ylw-pushpin"> 
     <IconStyle> 
      <scale>1.1</scale> 
      <Icon> 
       <href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href> 
      </Icon> 
      <hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/> 
     </IconStyle> 
    </Style> 
    <Style id="s_ylw-pushpin_hl"> 
     <IconStyle> 
      <scale>1.3</scale> 
      <Icon> 
       <href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href> 
      </Icon> 
      <hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/> 
     </IconStyle> 
    </Style> 
    <StyleMap id="m_ylw-pushpin"> 
     <Pair> 
      <key>normal</key> 
      <styleUrl>#s_ylw-pushpin</styleUrl> 
     </Pair> 
     <Pair> 
      <key>highlight</key> 
      <styleUrl>#s_ylw-pushpin_hl</styleUrl> 
     </Pair> 
    </StyleMap> 
    <Placemark> 
     <name>Untitled</name> 
     <styleUrl>#m_ylw-pushpin</styleUrl> 
     <LineString> 
      <tessellate>1</tessellate> 
      <coordinates> 
       -117.2983479390361,33.27144940863937,0 -117.2979479084534,33.27158154479859,0 -117.2974695164833,33.27172038778199,0 -117.2975027748323,33.27194103134417,0 -117.297514618297,33.27194834552386,0 -117.2979065026131,33.27210103585357,0 -117.2980671096438,33.27197757139673,0 -117.2980506390891,33.27176546338881,0 -117.2983889177018,33.27174732829762,0 -117.2985056013534,33.27196820309105,0 -117.2984607071796,33.27217535203514,0 -117.2982982520078,33.2722451382993,0 -117.2982714656408,33.2722496045722,0 -117.297926137081,33.27225329696987,0 -117.2979181624345,33.27225324047765,0 -117.297660871735,33.27222714260547,0 -117.2976362532899,33.2722186164706,0 -117.2974159727989,33.27218328409937,0 -117.2974081729552,33.27218350960742,0 -117.2970860609136,33.27208829299941,0 -117.2968393500826,33.27207716108421,0 -117.2967459496535,33.27216774204006,0 -117.2966603938058,33.27233920748802,0 -117.2969907889174,33.27237357387524,0 -117.2970232333844,33.27237306198914,0 -117.2973444433226,33.27239693646774,0 -117.297751764355,33.27242613992279,0 -117.2981731050047,33.27243373303686,0 -117.2981813185804,33.27243372905114,0 -117.2985617246156,33.2723816290589,0 -117.2987498163436,33.27248971415388,0 -117.2987694564539,33.27262188734785,0 -117.2985436721398,33.27267540671544,0 -117.2985270445518,33.27267612619851,0 -117.2981490803383,33.27268345629938,0 -117.2981145841072,33.2726829556605,0 -117.2977420026904,33.27265933276826,0 -117.2977334907908,33.27265936075214,0 -117.2977079525845,33.27265943947727,0 -117.297690884793,33.27265933069783,0 -117.2973143742666,33.2726410594433,0 -117.2972972842265,33.27263660852098,0 -117.2972803621663,33.27263663588342,0 -117.2969673713573,33.27262125275644,0 -117.296756583612,33.27260864705382,0 -117.2965634725893,33.27264899681126,0 -117.2965301429721,33.27279607660442,0 -117.296929900768,33.27282274189361,0 -117.2972917056901,33.27281884120617,0 -117.2975482260676,33.27280094439733,0 -117.2979485409129,33.27281652227333,0 -117.2983940432828,33.2728392485114,0 -117.2987809571886,33.27284381722371,0 
      </coordinates> 
     </LineString> 
    </Placemark> 
</Document> 
</kml> 

그리고 코드 :

from xml.dom import minidom 
import csv 

xmldoc = minidom.parse("Test.kml") 

kml = xmldoc.getElementsByTagName("kml")[0] 

document = kml.getElementsByTagName("Document")[0] 

placemarks = document.getElementsByTagName("Placemark") 

for placemark in placemarks: 
    coords = placemark.getElementsByTagName("coordinates")[0].firstChild.data 

    list = coords.split(",") 
    for items in list: 
     item = items.split(",") 
     for allitems in item: 
      latlon = allitems.replace("0 ","") 
      latlon = latlon.strip() 
      print(latlon) # <-- Printing to the screen works fine 
      with open("Output.csv", "w") as output: 
       writer = csv.writer(output, delimiter='\n') 
       writer.writerow(latlon) 

를 ****이 해결 **** 최종 작업 솔루션은 이것이다 :

with open("Output.csv", "w") as text_file:    # open the file first 
    #writer = csv.writer(output, delimiter='\n')  # and get ready to write 

    for placemark in placemarks: 
     coords = placemark.getElementsByTagName("coordinates")[0].firstChild.data 

     list = coords.split(",") 
     for items in list: 
      item = items.split(",") 
      for allitems in item: 
       latlon = allitems.replace("0 ","") 
       latlon = latlon.strip() 
       print(latlon) # <-- Printing to the screen works fine 
       text_file.write(latlon + '\n')  # Write the row to the already-open file 

나는 csv 방법을 포기하고 csv로 이름을 바꾼 텍스트 파일 출력과 함께 갔다. 나는 내가 필요한 결과를 얻게된다. 공헌 한 모든 것에 감사드립니다.

+2

반복 할 때마다 반복적으로 (w) 모드의 파일을 다시 여는 것을 알고 있습니까? – jonrsharpe

+0

jonrsharpe and Oliver W. 믿거 나 말거나, 나는 여기에서 끝나기 전에 몇 가지 다른 방법을 재구성했다. 파일을 한 번만 열면됩니다. 명백한 실수. – user3108489

답변

4

withwriter=은 루프 시작시 한 번 발생해야합니다. 지금은 마지막 항목을 버리고 각 항목에 대한 파일을 다시 만들고 있습니다.

with open("Output.csv", "w") as output:    # open the file first 
    writer = csv.writer(output, delimiter='\n')  # and get ready to write 

    for placemark in placemarks: 
     coords = placemark.getElementsByTagName("coordinates")[0].firstChild.data 

     list = coords.split(",") 
     for items in list: 
      item = items.split(",") 
      for allitems in item: 
       latlon = allitems.replace("0 ","") 
       latlon = latlon.strip() 
       print(latlon) # <-- Printing to the screen works fine 
       writer.writerow([latlon])  # Write the row to the already-open file 
         # EDIT 2^ ^

편집 지금 또 다른 문제가있을 수 있습니다 : 그것은 latlon 문자열처럼 보이지만 항목의 목록은 writerow 기대하고 자동으로 항목 사이에 쉼표를 채 웁니다. 특정 사용 사례에 따라 writer.writerow 대신 print(latlon + ',', file=output)을 원할 수 있습니다. 대신 latlon

편집 2 사용 [latlon] 행당 한 문자 대신 한 행에 전체 라인을 얻을 수 있습니다. 괄호는 한 번에 하나씩 문자 목록과 같이이 문맥에서 동작하는 문자열이 아닌 하나의 항목 목록으로 만듭니다.

+0

* "편집 후 따라야 할 코드"* - 대신 게시물을 클릭하기 전에 대답을 끝낼 수 있습니까? – jonrsharpe

+2

하지만 첫 번째 대답은 없었을 것입니다. ;) –

+0

@cxw 이것은 궁극적으로 내가 있어야 할 곳에있어. 고맙습니다. 예를 들어, 새 행의 목록에 각 항목의 모든 문자를 넣습니다. 또한 print (latlon + ',', file = output)는 구문 오류가 잘못되어 "=" – user3108489