oldoc63 / learningDS

Learning DS with Codecademy and Books
0 stars 0 forks source link

Reading a CSV file #360

Open oldoc63 opened 2 years ago

oldoc63 commented 2 years ago

Even though we can read the .csv lines as text without a problem, there are ways to access the data in a format better suited for programming purposes. In Python we can convert that data into a dictionary using the csv library's DictReader object.

oldoc63 commented 2 years ago

We first import our csv library, which gives us the tools to parse our CSV file. We then create the empty list of email addresses which we'll later populate with the email addresses from our CSV. Then we open users.csv file with the temporary variable users_csv.

We pass the additional keyword argument newline=' ' to the file opening open() function so that we don't accidentally mistake a line break in one of our data fields as a new row in our CSV.

After opening our new CSV file we use csv.DicReader(users_csv) which converts the lines of our CSV file to Python dictionaries which we can use access methods for. The keys of the dictionary are, by default, the entries in the first line of our CSV file. Since our CSV's first line calls the third field in our CSV "Email", we can use that as the key in each row of our DictReader.

When we iterate through the rows of our user_reader object, we access all of the rows in our CSV as dictionaries (except for the first row, which we used to label the keys of our dictionary). By accessing the 'Email' key of each of these rows we can grab the email address in that row and append it to our list_of_email_addresses.