Queer European MD passionate about IT

scourgify.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import csv
  2. import os
  3. import sys
  4. def main():
  5. try:
  6. input_file_name, output_file_name = sys.argv[1:3]
  7. except IndexError:
  8. print("Too few command-line arguments")
  9. sys.exit(1)
  10. if len(sys.argv) > 3:
  11. print("Too many command-line arguments")
  12. sys.exit(1)
  13. if not os.path.isfile(input_file_name): # Or try opening and catch FileNotFoundError
  14. print(f"Could not read {input_file_name}")
  15. sys.exit(1)
  16. if not input_file_name.endswith('.csv'):
  17. print(f"Not a CSV file")
  18. sys.exit(1)
  19. write_names_to_csv_file(read_names_from_csv_file(input_file_name), output_file_name)
  20. def read_names_from_csv_file(input_file_name):
  21. with open(input_file_name, 'r') as input_file:
  22. reader = csv.DictReader(input_file)
  23. for row in reader:
  24. yield row
  25. def write_names_to_csv_file(input_data, output_file_name):
  26. with open(output_file_name, 'w') as output_file:
  27. writer = csv.DictWriter(output_file, fieldnames=['first', 'last', 'house'])
  28. writer.writeheader()
  29. for row in input_data:
  30. row['last'], row['first'] = row['name'].split(', ')
  31. del row['name']
  32. writer.writerow(row)
  33. if __name__ == "__main__":
  34. main()