-
Notifications
You must be signed in to change notification settings - Fork 944
/
Copy pathwrite_csv.py
41 lines (29 loc) · 1.17 KB
/
write_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
import csv
import pandas as pd
def write_to_csv_files_using_DictWriter_class(data, fields, filename):
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames=fields)
# writing headers (field names)
writer.writeheader()
# writing data rows
writer.writerows(data)
def write_by_pandas(name_dict, filename, columns):
df = pd.DataFrame(name_dict, columns=columns)
print(df)
df.to_csv(filename, index=False)
return df
if __name__ == "__main__":
# my data rows as dictionary objects
mydata = [{'name': 'Noura', 'course': 'python40python401'},
{'name': 'Mahmoud', 'course': 'python401'},
{'name': 'Nizar', 'course': 'python401'},
{'name': 'Raneem', 'course': 'python401'},
{'name': 'Omer', 'course': 'python401'}, ]
# field names
fields = ['name', 'course']
# name of csv file
filename = "assets/course_name.csv"
# writing to csv file
print(write_to_csv_files_using_DictWriter_class(mydata, fields, filename))
print(write_by_pandas(mydata, filename, columns=fields))