[英]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.