forked from larymak/Python-project-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwrite_csv.py
45 lines (31 loc) · 1.23 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
42
43
44
45
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):
df = pd.DataFrame(name_dict)
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))
name_dict = {
'Name': ['Omar','Mahmoud','Noura','Raneem'],
'Score': [82,86,84,65]
}
print(write_by_pandas(name_dict))