2017-09-26 76 views
-1

首先讓我說我完全是Python新手,並且在編程方面的經驗很少。 我決定在工作中使用Python作爲一些工作自動化的環境。 我需要排序一些導出到XLS的日期,地理編碼地址,然後在Google API地圖或OpenSourceMaps上創建熱圖/人口地圖。我已經找到了SOME解決方案,但遇到了結合它們的問題,並且停留在非常有效的階段。Python 3.6輸出CVS文件爲空

請參閱我的代碼:

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的文件,之後顯現在地圖上標記我或羣體。

非常感謝您提供寶貴的建議。

回答

0

做一個標題列表,並將其在output_file.csv

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

這首寫將使CSV的標題第一行,然後輸出詞典將使用CSV的第一行每次涉及並添加數據相應地。

+0

你可以指出來哪裏把它在我的代碼。對於這樣一個簡單的問題抱歉。當我將它放在open('output_file ....)部分時,返回:TypeError:需要類似字節的對象,而不是'str' – Krystian

+0

剛剛定義了writer之後。並且在打印user_dict之後,確保使用writer命令將其寫入csv(您錯過了將dict寫入csv)。 –

+0

嗨Vinay,請參閱我的回覆帖子,顯示修改後的代碼。謝謝你的時間來幫助我。 – Krystian

0

,如果我理解你還有我的代碼應該是這樣的:

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()