Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. # GBTownsSortedByIncreasingPopulation
  2. # Reads and sorts data in order of increasing population
  3. # Writes this data to a seperate file
  4.  
  5. # Empty arrays for file
  6. place = [];
  7. Type = [];
  8. population = [];
  9. latitude = [];
  10. longitude = [];
  11.  
  12. opened = 0
  13.  
  14. try:
  15. readFile = open('GBplaces.csv','r');
  16. opened = 1
  17. except:
  18. print('Could not open file.');
  19.  
  20. # Skips headings of file
  21.  
  22. next(readFile);
  23.  
  24. # Using this as a check to see if the correct file is opened
  25. # Also used to see if it has sorted in right order when written
  26.  
  27. if opened:
  28. for line in readFile:
  29. splitUp = line.split(',');
  30. place.append(splitUp[0]);
  31. Type.append(splitUp[1]);
  32. population.append(int(splitUp[2]));
  33. latitude.append(splitUp[3]);
  34. longitude.append(splitUp[4]);
  35. print(splitUp[0] + ',' + splitUp[1] + ',' + splitUp[2] + ',' + splitUp[3] + ',' + splitUp[4]);
  36.  
  37. Headings = readFile.readline();
  38. readFile.close();
  39.  
  40. # Write a file which is sorted in population ascending order
  41. writeFile = open('GBplacesSorted.csv','w');
  42.  
  43. # sort population in acsending numerical order
  44. sortpopulation = sorted(population);
  45.  
  46. # sort each other array by zipping it with sorted population
  47. sortedplace = [place for (population,place) in sorted(zip(population,place), key=lambda pair: pair[0])];
  48. sortedType = [Type for (population, Type) in sorted(zip(population, Type), key=lambda pair: pair[0])];
  49. sortedlatitude = [latitude for (population,latitude) in sorted(zip(population, latitude), key=lambda pair: pair[0])];
  50. sortedlongitude = [longitude for (population, longitude) in sorted(zip(population, longitude), key=lambda pair: pair[0])];
  51.  
  52. # write a file which lists towns and cities in order of population (plus other info)
  53. writeFile.write(Headings);
  54. for i in range(0,len(place)):
  55. writeFile.write(str(sortedplace[i]) + ',' + str(sortpopulation[i]) + ',' + str(sortedType[i]) + ',' + str(sortedlatitude[i]) + ',' + str(sortedlongitude[i]));
  56. writeFile.close();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement