Tuesday, November 15, 2022

Files 1 - Python Programming for Beginners Practice Exercise 12

Exercise 12:

Read the contents of animals.txt and produce a file named animals­sorted.txt that is sorted alphabetically.

The contents of animals.txt:

  1. man
  2. bear
  3. pig
  4. cow
  5. duck
  6. horse
  7. dog

Sample Output:

  1. bear
  2. cow
  3. dog
  4. duck
  5. horse
  6. man
  7. pig

Solution:

  1. #!/usr/bin/env python3
  2.  
  3. unsorted_file_name = 'animals.txt'
  4. sorted_file_name = 'animals-sorted.txt'
  5. animals = []
  6.  
  7. try:
  8. with open(unsorted_file_name) as animals_file:
  9. for line in animals_file:
  10. animals.append(line)
  11. animals.sort()
  12. except:
  13. print('Could not open {}.'.format(unsorted_file_name))
  14.  
  15. try:
  16. with open(sorted_file_name, 'w') as animals_sorted_file:
  17. for animal in animals:
  18. animals_sorted_file.write(animal)
  19. except:
  20. print('Could not open {}.'.format(sorted_file_name))

No comments:

Post a Comment