繁体   English   中英

Python 3.6 输出 CVS 文件为空

[英]Python 3.6 output CVS file is empty

首先让我说我对 Python 完全陌生,并且在编程方面经验很少。 我决定在我的工作中使用 Python 作为一些工作自动化的环境。 我需要对导出到 XLS 的一些日期、地理编码地址进行排序,然后在 google API 地图或 OpenSourceMaps 上创建热图/人口地图。 我已经找到了一些解决方案,但在将它们组合起来时遇到了问题,并且停留在非常早期的阶段。

请看我的代码:

import os
import pandas
import geopy
import urllib
import csv
import numpy
import geopy

# - - - - - - - - -

fin = open ("source_file.csv","r") # open input file for reading 
users_dict = {}
with open('output_file.csv', 'wb') as fout: # output csv file
    writer = csv.writer(fout)
    with open('source_file.csv','r') as csvfile: # input csv file
        reader = csv.DictReader(csvfile, delimiter=',')
        for row in reader:
            location_string = row['city'] + ',' + row['street'] + ' ' + row['house']
            from geopy.geocoders import Nominatim
            geolocator = Nominatim()
            location = geolocator.geocode(location_string) 
            row['lat']=latitude = location.latitude
            row['lng'] = location.longitude
            users_dict.update(row)
            print (users_dict)
        fout.close()
fin.close()

输入文件格式

unit_no,kod,street,house,city,lng,lat
123456,00-001,nowy swiat,4,warszawa,,

字典输出:

{'unit_no': '123456', 'kod': '00-001', 'street': 'nowy swiat', 'house': '4', 'city': 'warszawa', 'lng': 21.0220598, 'lat': 52.2302825}

结果: output_file.csv 是零大小 output_file.csv 打开

带有数据的预期输出文件:

unit_no,kod,street,house,city,lng,lat
123456,00-001,nowy swiat,4,warszawa,21.0220598,52.2302825

在我看来,下一阶段是从创建的输出创建 geojson 文件,然后在地图上可视化我的标记或人口。

在此先感谢您的宝贵建议。

制作一个标题列表并首先将其写入 output_file.csv

header = ['unit_no','kod','street','house','city','lng','lat']
writer.writerow(header)

这将使csv的标题第一行,然后输出字典每次都会与csv的第一行相关联并相应地添加数据。

如果我理解你,我的代码应该是这样的:

with open('output_file.csv', 'wb') as fout: # output csv file
    writer = csv.writer(fout)
    header = ['unit_no','kod','street','house','city','lng','lat']  # your suggestion
    writer.writerow(header)   # your suggestion
    with open('source_file.csv','r') as csvfile: # input csv file

并完成:

        print (users_dict)
        writer = csv.DictWriter(fout, delimiter=',') # your suggestion
        writer.writerows(user_dict) # your suggestion
        fout.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM