【问题标题】:how do i write a new row after reading each file? [duplicate]读取每个文件后如何写一个新行? [复制]
【发布时间】:2019-12-16 06:33:39
【问题描述】:

我想在读取每个文件后写一个新行。这是从 KML 到 CSV。

当天: - 每个文件都应将值写入列 - 每个 kml 文件的新行

from bs4 import BeautifulSoup
import csv
import os
import glob

def process_coordinate_string(str):

    comma_split = str.split(',')
    return [comma_split[1].strip(), comma_split[0].strip()]


def main():
    """
    Open the KML. Read the KML. Open a CSV file. Process a coordinate string to be a CSV row.
    """

    files = []
    for i in os.listdir('<dir>'):
        if i.endswith('.kml'):
            with open(i, 'r') as f:
                s = BeautifulSoup(f, 'xml')
                with open('out.csv', 'w') as csvfile:
                    writer = csv.writer(csvfile,lineterminator='')
                    for names in s.find_all('name',):
                        writer.writerow(names)

                    for coords in s.find_all('coordinates'):
                        writer.writerow(process_coordinate_string(coords.string))



main()

【问题讨论】:

    标签: python csv gis kml


    【解决方案1】:

    使用

    with open('out.csv', 'a') as csvfile:
    

    而不是

    with open('out.csv', 'w') as csvfile:
    
    
    
    from bs4 import BeautifulSoup
    import csv
    import os
    import glob
    
    def process_coordinate_string(str):
    
        comma_split = str.split(',')
        return [comma_split[1].strip(), comma_split[0].strip()]
    
    
    def main():
        """
        Open the KML. Read the KML. Open a CSV file. Process a coordinate string to be a CSV row.
        """
    
        files = []
        for i in os.listdir('.'):
            if i.endswith('.kml'):
                with open(i, 'r') as f:
                    s = BeautifulSoup(f, 'xml')
                    with open('out.csv', 'a',) as csvfile:
                        writer = csv.writer(csvfile,lineterminator='')
                        for names in s.find_all('name',):
                            writer.writerow(names)
    
                        for coords in s.find_all('coordinates'):
                            writer.writerow(process_coordinate_string(coords.string))
    
                            print(dir(writer))
                        writer.writerow("\n")
    
    
    
    main()
    

    【讨论】:

    • 这给了我一个新的行。相反,我想要这个:例如1.kml 所有值 1 行,多列。 2.kml第2行,多列
    • 好的,谢谢!为你投票!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 2013-07-12
    相关资源
    最近更新 更多