Introduction to Python Import CSV
In this article, we will see CSV is elaborated as comma-separated-values which is used to store tabular data or spreadsheet file format, which uses comma as delimiter or separator, and such files are known as CSV files. In Python, to parse or work with such CSV files, we need to import the CSV module, an inbuilt module. To do this, we need to use the “import” keyword before “csv” to support CSV files or to parse CSV files in python. This csv module in Python is used to read or write or handle CSV files; to read or write such files, we need to loop through the CSV file rows.
Working of CSV Module in Python
In this article, we will see how to import the csv module in Python. In Python, csv is an inbuilt module used to support CSV files, such as reading CSV files. Therefore to extract data from a CSV file, we have to loop through rows, and we also have to use split methods to extract data from each column which are separated by commas.
Now let us see how to import the csv module.
import CSV
This statement is used for importing a csv module that is used for parsing tabular like data structure such as data in excel format, and these files are saved in .csv extension; this csv modules provide various classes for reading and writing data to CSV files. Now we will see various csv module functions and classes in the below section.
Examples to Implement Python Import CSV
Below are the examples of Python Import CSV:
Example #1
Reading CSV File using CSV Module Function as csv.reader()
This function is used to extract data from CSV files to read and print the output screen data. To do this, we need to create a reader object; then, the function will read each line of the CSV file and make the list of columns and print it. We can read CSV files that are separated from any other delimiter other than comma-separated files.
Now will see how to read CSV file and is demonstrated in the below example:
Code:
import csv
print("Program to demonstrate csv.reader() function:")
print("\n")
c = open('company.csv','r')
print("The csv file is opened for reading:")
print("\n")
o = csv.reader(c)
print("The contents of the above file is as follows:")
for r in o:
print (r)
c.close()
Output:
Explanation: In the above program, we can see we are reading file company.csv, which is already present in the current directory where the python software is present using an open() function with read mode ‘r’. and the output displays the content of the file. This function gives No such file or directory as an error message if the file does not exist.
Example #2 – Writing to the File using csv.writer()
This function is used to write the data to the file. This function can also be used to create a new file and open it in the write mode ‘w’. Let us demonstrate this function in the below example.
Code:
import csv
print("Program to demonstrate csv.writer() function")
print("\n")
p_details =[('course','fees','place'),('Python',22000,'Pune'),('Android',11000,'Assam'),('Java',30000,'Delhi')]
c = open('programs.csv','w')
print("File is opened for writing:")
o = csv.writer(c)
for p in p_details:
o.writerow(p)
c.close()
Output:
Explanation: In the above program, we can see we are writing details of programming courses, and we have opened a file named ‘programs.csv’ in write mode ‘w’, which first creates a file, and then the details are written to the file. And in the output screen, we can see it will print saying the file is opened for writing, and when we open the file, we can see it in CSV format as shown in the above screenshot, where each data is written in separate columns and row. Note that CSV uses excel as the default output to display the CSV file.
We will now see classes provided by the Python csv module for reading from and writing to a CSV file. DictReader and DictWriter are similar to reader and writer functions as in the above section. But these classes use dictionary objects to read and write CSV files. Now will see these classes in the below section.
Example #3 – DictReader
This class uses a dictionary object which is created for mapping the data to read it to the dictionary whose key is given by field names, but if the keys are not defined or declared, then by default, it will take first row data as keys of the dictionary. Let us demonstrate in the below example.
Code:
import csv
print("Program to demonstrate DictReader() class")
print("\n")
with open('company.csv') as c:
r = csv.DictReader(c)
for row in r:
print(row['Name'], row['Age'])
Output:
Explanation: In the above program, we can see that we are using DictReader() function, which will read the file company.csv, and this will print only those which keys are specified, such as “Name” and “Age” are the keys of the dictionary which is a company.csv file content. So in the above screenshot of output, only the contents of “Name” and “age” are displayed.
Example #4 – DictWriter
This class is also similar to the writer() function. In this class, this also specifies the keys of the dictionary through “fieldnames” as these keys are optional in the above DictReader, but keys are must be specified to avoid ambiguity when writing the data to the CSV file.
Let us demonstrate in the below example.
Code:
import csv
print("Program to demonstarte DictWriter() class")
print("\n")
with open('Game.csv', 'w') as file:
columnnames = ['Game_name', 'No_of_players']
writer = csv.DictWriter(file, fieldnames=columnnames)
writer.writeheader()
writer.writerow({'Game_name': 'Cricket', 'No_of_players': 12})
writer.writerow({'Game_name': 'Football', 'No_of_players': 11})
writer.writerow({'Game_name': 'Hockey', 'No_of_players': 11})
Output:
Explanation: In the above program, we can see we have created a new file “Game.csv” in write mode “w” by using an open() function, and then we use DictWriter() to write the data to the file, and here we mention the column names as field names which are the keys for the dictionary created. In the above output, we can see how the file is created and the data is written to it.
Conclusion
This article concludes that the CSV module in Python is used to work with CSV(comma separated values) files. CSV modules are also used in many applications in the data science subjects using the pandas concept in Python. This article saw how to read from and write to CSV files using this csv module. In this, we also saw a few CSV functions such as reader() and writer() functions and classes such as DictReader() and DictWriter(), which are created as dictionaries along with keys as field names.
Recommended Articles
This is a guide to Python Import CSV. Here we discuss a brief overview of Python Import CSV and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –