First page Back Continue Last page Overview Graphics

Exercise

Write a program, which directly reads in the file bundeslaender.txt from the internet location and creates a new file with the following format:

„land area population population per square km“

import urllib.request

url = "http://www.python-course.eu/material/texts/bundeslaender.txt"

fh = urllib.request.urlopen(url)

fhw = open("bundeslaender.txt", "w")

fh.readline()

for line in fh:

line = line.decode("iso8859-1") # "utf-8"

land, area, male, female = line.split()

population = int(male) + int(female)

area_sq_km = float(area) / population

output = land + " " + str(area)

output += " " + str(population) + " " + str(area_sq_km)

fhw.write( output + "\n" )

fh.close()

fhw.close()