-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle_csv.py
52 lines (41 loc) · 1.5 KB
/
handle_csv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/python3
'''
create_csv.py
Creates a CSV from an array.
The file also have a example function for saving some info
The function can be included in other scripts like this:
from handle_csv import create_csv_file
result, csv_file_name = create_csv_file(MY_FILE)
'''
import csv
def create_csv_file(csv_array, file_name, verbose=0):
# Specify the CSV file name
csv_file_name = "./" + file_name
# Check if csv_array is not empty
if not csv_array:
if verbose > 0:
print("Error: The csv_array is empty.")
return "CSV creation failed: csv_array is empty.", None
# Get the fieldnames from the first dictionary
fieldnames = csv_array[0].keys()
# Open the CSV file for writing
with open(csv_file_name, mode='w', newline='') as file:
# Create a DictWriter object
writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write the header (field names)
writer.writeheader()
# Write the rows (data)
for row in csv_array:
writer.writerow(row)
if verbose > 0:
print(f" Data saved in {report_file_name}")
return "CSV created successfully: " + csv_file_name, csv_file_name
## Start
if __name__ == "__main__":
csv_array = [
{"Name": "Alice", "Age": 23, "Grade": "A"},
{"Name": "Bob", "Age": 22, "Grade": "B"},
{"Name": "Charlie", "Age": 24, "Grade": "C"},
]
csv_file = "your_file.csv"
result, csv_file_name = create_csv_file(csv_array, csv_file)