Heyy, how are you doing? Hope you had an amazing week. I am back with another Python lesson. Today we will be learning about csv files and how to edit them, open them and in general, work with them using Python. But first let us understand, what is a csv file?
We all have
seen those excel spreadsheets, right? Well csv files have a similar format in
organizing and showing data. In fact, you can use MS-Excel to open these kinds
of files. So in other words, today we will be learning how to convert a normal
data into an organised and readable spreadsheet. This lesson will be especially
helpful to analysts and people who are almost every day stuck with MS-Excel. After going through this article, you may be able to automate all those boring entries with
Python.
WHAT IS A CSV FILE?
A csv file is a file with a ‘.csv’ extension that separates data using comma (,). CSV stands for Comma Separated Values. Programmers commonly use csv files in their programs when they are working with data.
Every data
separated by a comma represents a cell in the spreadsheet (Cells are those
blocks where you input values in a spreadsheet), and each line represents a row
in the spreadsheet. So, basically commas create columns and lines represent
rows.
You can
change the character with which you separate values. These characters are
called Delimiters. Delimiter is a symbol
like a comma (,) or a period (.) used to separate data in a csv file.
Now, let us
take a look at an example. The contents of a csv file looks like:
One,Two,Three
Four,Five,Six
When this
file is opened as a spreadsheet using applications like MS-Excel, it will look
like:
|
One |
Two |
Three |
|
Four |
Five |
Six |
WRITING TO
A CSV FILE:
So far we
have learnt, what a csv file is and how normal text looks like in a csv file.
Now let us learn about editing/writing to a csv file. In order to work with csv
files, we must import a module called ‘csv’ which is packed with functions that
help us work with these kinds of files. If you do not know about modules or how to import
them, you can find all that knowledge in this small article PYTHON BEGINNER’S GUIDE | MODULE.
We can open
a csv file in Python, just like a normal file, with the open() function (if you
have no idea what I am talking about, you should probably check this out: PYTHON INTERMEDIATE’S GUIDE |WORKING WITH FILES – PART II). Once you have opened the file you can start writing to it.
csv.writer()
FUNCTION:
The ‘csv’
module has a function called ‘writer()’, which can be used to write to csv
files. Yeah..... I know, they could have simply called it the write() function,
but they decided to go with writer(), just to make stuff complicated for us.
The writer()
method accepts two parameter. First is the file object/the variable in which
you have stored the file object and the second is the delimiter. So the syntax
looks like this:
Syntax: csv.writer(file_object,delimiter=’<delimiter>’)
Example: with open('test.csv',’w’) as f:
write = csv.writer(f, delimiter= ‘,’)
writerow()
METHOD:
So far, we
have specified the file we want to edit and the delimiter we want to use. Now
let us learn how to add a row with some values. For this, we use the writerow()
function.
The
writerow() method creates a new row and is used on the object the writer()
function returns (This may seem confusing but I’ll explain it when we take a
look at an example). The writerow() method takes a list
of values as a parameter. Each item you put in the list will be a column in the
new row you create in the spreadsheet.
This whole
thing will be clearer once we take a look at an example and you guys can try it
out for yourself.
Syntax: writer_object.writerow([list_of_values])
Example: with open(‘test.csv’,’w’) as f:
write
= csv.writer(f, delimiter= ‘,’)
write.writerow([‘one’,’two’,’three’])
Here, we have inputted a list as a parameter and all the values are separated by commas. We have specifically used commas to separate the values because we have declared comma as a delimiter. So, the comma tells Python that each value separated by the comma, will be inputted in a new cell in the spreadsheet. Obviously, you can change the delimiter and add as many rows as you want with the writerow() function. If you want to create a large number of rows, you can use loops to help you out.
READING A
CSV FILE:
Since, you
have learnt writing to a csv file, let us learn how to read a csv file? For
this we will use a function from the csv module, reader() function.
reader() FUNCTION:
To read a csv file, we must first open the file like we did
when writing to the file. Let’s take a look at the syntax and an example:
Syntax: csv.reader(file_object,delimiter=’<delimiter>’)
Example: with open(‘test.csv’,’r’) as f:
read
= csv.reader(f, delimiter= ‘,’)
for row in read:
print(‘,’.join(row)
The reader()
method form the ‘csv’ module will read the file and return an iterable, which
we iterate through using the for loop.(You can read this article to learn more
about the for loop: PYTHON BEGINNER’S GUIDE | FOR LOOPS)
The join()
method in the loop is used to join each piece of data with a comma (,). (You
can learn more about the join() method and other methods that help in
manipulating strings with this article PYTHON BEGINNER’S GUIDE | MANIPULATING STRINGS)
CONGRATULATIONS !!! You now know how to read & write to csv files using Python. I am really glad to share this knowledge with you. Like I always say, Have fun with it !!! Create some cool programs. Good luck !!!!
So, this was how to work with csv files using Python. Stay tuned for another article next week, same time, where we will learn about Object Oriented Programming. So more cool stuff coming your way, DON’T MISS IT !!
I hope this article answered all of your questions and even helped you in becoming a better programmer. IF IT DID, leave a like AND FOLLOW THIS BLOG TO BECOME A PROFESSIONAL PYTHON PROGRAMMER FROM A TOTAL BEGINNER. IF IT DIDN'T, feel free to ask any further queries in the comment section below.
HOPE YOU HAVE AN AWESOME DAY AHEAD !!!


0 Comments
Welcome to the comments section, this is where you can contact me personally for any doubts or feedback