I am new to python so I decided to write a script that parses a json array and writes data in a file.
I wrote the code that does that but I think it can be done way better, So I was hoping to get feedback on how this code can be enhanced and more inline with python best practices.
from urllib2 import urlopen
import json
def get_json(url):
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
url = ("http://api.goeuro.com/api/v2/position/suggest/en/Berlin")
json_array = get_json(url)
f = open('data.txt', 'w')
for x in json_array:
gp = x["geo_position"]
l = gp["latitude"]
o = gp["longitude"]
f.write(unicode(x["_id"]).encode("utf-8") +", " + unicode(x["name"]).encode("utf-8") + ", " + unicode(x["type"]).encode("utf-8")+ ", " + unicode(l).encode("utf-8") + ", " + unicode(o).encode("utf-8") + unicode("\n").encode("utf-8"))
f.close()
Also, what is the best way for not having an empty new line at the end of the file ?