import csv
def export_lists_to_csv(data_list, filename="results.csv", fieldnames=None):
"""
Exports a list of lists to a CSV file. Handles empty lists and missing fieldnames.
Args:
data_list (list of lists): The data to export.
filename (str): The name of the CSV file to create. Defaults to "results.csv".
fieldnames (list): A list of fieldnames for the CSV header. If None,
the first row of data is used as headers.
"""
if not data_list:
print("Warning: Input list is empty. No CSV file will be created.")
return
try:
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
if fieldnames is None:
fieldnames = data_list[0] # Use first row as headers
writer.writerow(fieldnames)
for row in data_list:
writer.writerow(row)
except Exception as e:
print(f"Error exporting to CSV: {e}")
if __name__ == '__main__':
# Example usage:
data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'London'],
['Charlie', 35, 'Paris']
]
export_lists_to_csv(data, "people.csv")
# Example with no header and specific filename
data2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
export_lists_to_csv(data2, "numbers.csv", fieldnames=['col1', 'col2', 'col3'])
# Example with empty list
empty_data = []
export_lists_to_csv(empty_data, "empty.csv")
Add your comment