You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 93d5e4e
Browse filesBrowse the repository at this point in the historyBrowse files
# Provides functions for reading and writing data in CSV format
5
+
# Reading data is done using the reader object
6
+
# Writing is done using the writer object
7
+
8
+
9
+
10
+
## .reader()
11
+
# returns an object that allows us to iterate over each line in the CSV file
12
+
# we need to pass a file object to the reader function. For this purpose, we can use a built-in function called open. Look at the code in the editor and run it.
13
+
14
+
importcsv
15
+
16
+
withopen('contacts.csv', newline='') ascsvfile: # Open the CSV file
17
+
reader=csv.reader(csvfile) # Create a CSV reader object
18
+
print(reader)
19
+
# <_csv.reader object at 0x0000018332537EE0>
20
+
21
+
# The output shows that the reader object has been created successfully
22
+
# However, to see the actual data in the CSV file, we need to iterate over the reader object
23
+
24
+
#=> Iterating over the reader object
25
+
importcsv
26
+
27
+
withopen('contacts.csv', newline='') ascsvfile: # Open the CSV file
28
+
reader=csv.reader(csvfile, delimiter=',') # Create a CSV reader object, delimiter=',' is the default
29
+
forrowinreader:
30
+
print(row) # Iterate over each row in the CSV file and print it
31
+
'''
32
+
['Name', 'Phone']
33
+
['mother', '222-555-101']
34
+
['father', '222-555-102']
35
+
['wife', '222-555-103']
36
+
['mother-in-law', '222-555-104']
37
+
'''
38
+
39
+
#=> Joining the elements of each row
40
+
importcsv
41
+
42
+
withopen('contacts.csv', newline='') ascsvfile:
43
+
reader=csv.reader(csvfile, delimiter=',')
44
+
forrowinreader:
45
+
print(','.join(row)) # Join the elements of each row with a comma and print
46
+
'''
47
+
Name,Phone
48
+
mother,222-555-101
49
+
father,222-555-102
50
+
wife,222-555-103
51
+
mother-in-law,222-555-104
52
+
'''
53
+
54
+
#=> Using the DictReader class
55
+
importcsv
56
+
57
+
withopen('contacts.csv', newline='') ascsvfile:
58
+
reader=csv.DictReader(csvfile) # Create a CSV DictReader object
59
+
forrowinreader:
60
+
print(row['Name'], ':', row['Phone'])
61
+
'''
62
+
mother : 222-555-101
63
+
father : 222-555-102
64
+
wife : 222-555-103
65
+
mother-in-law : 222-555-104
66
+
'''
67
+
68
+
importcsv
69
+
70
+
withopen('contacts.csv', newline='') ascsvfile:
71
+
fieldnames= ['Name', 'Phone'] # Define the field names
72
+
reader=csv.DictReader(csvfile, fieldnames=fieldnames) # Create a CSV DictReader object with field names
73
+
forrowinreader:
74
+
print(row['Name'], row['Phone']) # Print the values associated with 'Name' and 'Phone'
75
+
'''
76
+
Name Phone
77
+
mother 222-555-101
78
+
father 222-555-102
79
+
wife 222-555-103
80
+
mother-in-law 222-555-104
81
+
'''
82
+
83
+
84
+
## writer()
85
+
# Saving data to a CSV file is done using the writer object provided by the csv module
86
+
# Takes the same set of arguments as the reader function
writer=csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) # quotechar and quoting to handle special characters
92
+
# Due to csv.QUOTE_MINIMAL, this field will be automatically quoted to preserve the comma as part of the data, not as a delimiter
93
+
writer.writerow(['Name', 'Phone'])
94
+
writer.writerow(['mother', '222-555-101'])
95
+
writer.writerow(['father', '222-555-102'])
96
+
writer.writerow(['wife', '222-555-103'])
97
+
writer.writerow(['mother-in-law', '222-555-104'])
98
+
writer.writerow(['grandmother, grandfather', '222-555-105']) # Comma in the name
99
+
# The above code creates a CSV file named exported_contacts.csv and writes the data to it
100
+
# The quotechar and quoting parameters can be used to handle special characters in the data
101
+
# ==> csv file
102
+
'''
103
+
Name,Phone
104
+
mother,222-555-101
105
+
father,222-555-102
106
+
wife,222-555-103
107
+
mother-in-law,222-555-104
108
+
"grandmother, grandfather",222-555-105"
109
+
'''
110
+
111
+
#=> quoting
112
+
# specifies what values should be quoted
113
+
# csv.QUOTE_MINIMAL == only values with special characters (such as delimiter or quotechar) will be quoted (default)
114
+
# csv.QUOTE_ALL == quotes all values
115
+
# csv.QUOTE_NONNUMERIC == quotes only non-numeric values
116
+
# csv.QUOTE_NONE == doesn't quote any values. It's not a good idea to set this value if we have special characters that require quoting, because this will raise an error
117
+
118
+
# NOTE: The quotechar and quoting parameters can also be used in the reader function. See the documentation for more information.
# 1st = logging level equal to CRITICAL ==> only messages with this level will be processed
89
+
# 2nd = passing a filename to the second argument creates a FileHandler object instead of a StreamHandler object
90
+
# the logs no longer appear in the console, after setting the filename argument, all logs will be directed to the specified file
91
+
# 3rd = passing the last filemode argument with the value 'a' (default mode) means that new logs will be appended to this file
92
+
93
+
94
+
logger=logging.getLogger()
95
+
96
+
logger.critical('Your CRITICAL message')
97
+
logger.error('Your ERROR message')
98
+
logger.warning('Your WARNING message')
99
+
logger.info('Your INFO message')
100
+
logger.debug('Your DEBUG message')
101
+
102
+
# Only the CRITICAL message will be logged to the 'prod.log' file
103
+
# files contains:
104
+
'''
105
+
CRITICAL:root:Your CRITICAL message
106
+
'''
107
+
108
+
109
+
## Logging with a specific format
110
+
111
+
importlogging# import the logging module
112
+
113
+
FORMAT='%(name)s:%(levelname)s:%(asctime)s:%(message)s'# define the log format
114
+
115
+
logging.basicConfig(level=logging.CRITICAL, filename='prod.log', filemode='a', format=FORMAT) # configure logging to write to 'prod.log' with CRITICAL level and specified format
0 commit comments