1. import csv
  2. def export_lists_to_csv(data_list, filename="results.csv", fieldnames=None):
  3. """
  4. Exports a list of lists to a CSV file. Handles empty lists and missing fieldnames.
  5. Args:
  6. data_list (list of lists): The data to export.
  7. filename (str): The name of the CSV file to create. Defaults to "results.csv".
  8. fieldnames (list): A list of fieldnames for the CSV header. If None,
  9. the first row of data is used as headers.
  10. """
  11. if not data_list:
  12. print("Warning: Input list is empty. No CSV file will be created.")
  13. return
  14. try:
  15. with open(filename, 'w', newline='') as csvfile:
  16. writer = csv.writer(csvfile)
  17. if fieldnames is None:
  18. fieldnames = data_list[0] # Use first row as headers
  19. writer.writerow(fieldnames)
  20. for row in data_list:
  21. writer.writerow(row)
  22. except Exception as e:
  23. print(f"Error exporting to CSV: {e}")
  24. if __name__ == '__main__':
  25. # Example usage:
  26. data = [
  27. ['Name', 'Age', 'City'],
  28. ['Alice', 30, 'New York'],
  29. ['Bob', 25, 'London'],
  30. ['Charlie', 35, 'Paris']
  31. ]
  32. export_lists_to_csv(data, "people.csv")
  33. # Example with no header and specific filename
  34. data2 = [
  35. [1, 2, 3],
  36. [4, 5, 6],
  37. [7, 8, 9]
  38. ]
  39. export_lists_to_csv(data2, "numbers.csv", fieldnames=['col1', 'col2', 'col3'])
  40. # Example with empty list
  41. empty_data = []
  42. export_lists_to_csv(empty_data, "empty.csv")

Add your comment