Python

How to read a csv file in Python

April 4, 2022

How to read a csv file in Python

In this article you will learn the best ways to read a csv file in Python – so you can use the data structure as you wish to!

read a csv file in Python thumb

Hey you programmer, ok? Let’s learn more about the csv structure in Python!

The csv structure has become predominant in data files

Especially when we are talking about Data Science, data set files usually come in the csv extension

Therefore, learning how to read and handle these files with Python is of great help.

So with csv library we can read csv files with Python

Let’s see a practical example:

import csv

with open('flights.csv', newline='') as csvfile:
 spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
 for row in spamreader:
  print(', '.join(row))

This way you will be able to print all your lines from the csv file

The ”with” statement tries to open the file, which here in the example we use flights.csv

We assign the file to the csv file variable, and then use the reader method on it, so that the file can be read

In the for loop structure, we print each line of the csv file

Or rather, we print the lines according to the delimiter

Conclusion

In this article we learned how to read a csv file in Python

We use the csv library, which is from Python itself and helps a lot when reading files that have the comma-separated values pattern

It is important to remember that the library is very complete, I suggest you look at its documentation to learn the other methods, which are essential

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x