The Python documentation recommends using
withwhen dealing with files at the bottom of 7.2.1 of the Python tutorial, this has the benefit that you do not have to close the file yourself.Although not necessary often a main function is made, so that the other functions also can be used as a module. (6.1.1. Executing modules as scripts)
The long line with the
writestatement can be split over multiple lines, you do not need the line joining character (/\) in this case because, a closing bracket is still expected at the end of the line.The newline problem, and simular problems can be solved with the join function of strings
I took the liberty to create an extra function and all and all i changed your code to:
from urllib2 import urlopen
import json
def get_json(url):
response = urlopen(url)
data = response.read().decode("utf-8")
return json.loads(data)
def json_to_formatted_text(geo_data):
formatted_lines = []
for x in geo_data:
gp = x["geo_position"]
l = gp["latitude"]
o = gp["longitude"]
line = (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"))
formatted_lines.append(line)
return unicode("\n").encode("utf-8").join(formatted_lines)
def main():
url = ("http://api.goeuro.com/api/v2/position/suggest/en/Berlin")
json_array = get_json(url)
out_text = json_to_formatted_text(json_array)
with open('data.txt', 'w') as f:
f.write(out_text)
if __name__ == "__main__":
main()