How to Read a CSV File in Python: 5…
In this post, you will learn how to read a CSV (.csv) file with Python in 7 simple steps. Note, the first steps they include localizing your file (1), creating a Python string variable pointing to the file (and location; 2), and three 2 importing the module to read the CSV file.
1. Get the File Location
In the first step to read a CSV you need to find the file.
Of course, you usually know this when working with CSV files in Python.
2. Create a Python String
In the xecond step, you create a Python string pointing to the file. For example, <code>csv_file = ‘DATA.csv'</code>
3. Import the CSV Module
In the third step, we will import the csv module that we are going to use to read the csv file with.
import csv
4. Read the CSV File with Python
In the fourth step, just use the reader method from Pythons csv module:
with open(csv_file) as data:
csv_data = csv.DictReader(data,
delimiter=',')
Note, in the above code example you read the data as an ordered dictionary. In the final step, you will learn how to also save this as a list of dictionaries.
Of course, if you plan to work with the data (e.g., make barplots with Seaborn) you should really work with Pandas dataframes to load the csv file.
5. Bonus: Print the Data
In the fifth, and final, step we can print the data from the file. Note, that your data is in the “csv_data” variable.
with open(csv_file) as data:
csv_data = csv.DictReader(data,
delimiter=',')
csv_dict = [dict(row) for row in csv_data]
print(csv_dict)
In this post, you have learned how to read a csv file with Python. Specifically, you learned 5 simple steps on how to load a csv file using Python. In more recent posts, you can learn, by examples, how to visualize data in Python using Seaborn.