Introduction to Python Import CSV
In this post, we shall learn that CSV stands for comma-separated values, a file format for storing tabular data or spreadsheets that employs commas as delimiter or separator. The CSV module is a built-in Python module that may be used to read and manipulate CSV files. To read or write CSV files in Python, the “import” keyword must be used before the “csv” file extension. Python’s csv module may be used to read, write, and otherwise manipulate CSV files; doing so requires a looping action over the file’s contents.
rows.
Working of CSV Module in Python
This post will demonstrate how to load the csv module into a Python environment. Python’s csv module provides built-in functionality for working with CSV files and may be used to do tasks like reading CSV files. The data in a CSV file is stored in columns that are separated by commas; thus, we must loop over rows and utilise split techniques to extract data from each column.
Let’s have a look at importing the.csv file.
module.
import CSV
This line imports a csv module for working with tabular data structures, such as those found in Excel spreadsheets, and other files stored in the.
file format with the.csv suffix; these.csv modules provide a variety of classes for working with CSV files. In the sections that follow, we’ll examine the many classes and functions available in the csv module.
section.
Examples to Implement Python Import CSV
Python Import Examples are shown below.
CSV:
CSV File Reading using
Example #1
‘s csv.reader Function from the CSV Module ()
Use this method to read and print CSV files to the screen. Then, a reader object is created, and then the CSV file is read line by line to generate the list of columns. In addition to comma-separated files, we can also read CSV files that are separated by any other delimiter.
In the next example, you’ll learn how to read a CSV file. Code:
Product 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()
Explanation: The preceding code uses the open() function with the read mode ‘r’ to read the file company.csv, which is located in the current directory where the python software is located. It is then shown in the output. If the specified file does not exist, this method will return the error message “No such file or directory.”
exist.
Example #2 – Writing to the File using csv.writer()
Information for a file is written using this function. When used in conjunction with the ‘w’ write mode, this method may also be used to generate a brand-new file. Here’s an illustration of this feature in action. Code:
import csv
Productiveness:
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()
Explanation: As can be seen in the code above, the specifics of programming classes are being recorded by opening the file ‘programs.csv’ in write mode ‘w,’ which first generates the file and then writes the information to it. It will indicate on the output screen that the file is open for writing, and when you open the file, you’ll notice that the data is laid out in columns and rows, much as in the preceding picture, in a format called comma separated values (CSV). Keep in mind that CSV files are often viewed in Excel.
The Python csv package now displays classes for working with CSV files. Similar to the reader and writer operations described above, DictReader and DictWriter are available. Yet, dictionary objects are used by these classes to read and write CSV files. You may check out these courses below.
section.
Example #3 – DictReader
If the keys are not declared or specified, this class will use the data from the first row of the table as the keys of the dictionary. This class utilises a dictionary object that is constructed for mapping the data to read it to the dictionary whose key is supplied by field names. Let’s use the case study below to illustrate. Code:
Production 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'])
Explanation: The preceding code uses the DictReader() function, which reads the file company.csv and only prints the entries whose keys match the ones supplied. In this case, “Name” and “Age” are the keys of the dictionary whose content is the contents of the company.csv file. Thus, just “Name” and “age” data are shown in the output snapshot above.
displayed.
Example #4 – DictWriter
The writer() method and this category have similarity. This class additionally uses “fieldnames” to provide the dictionary’s keys; although these keys are optional in the aforementioned DictReader, they must be given when publishing to a CSV file to prevent any ambiguity.
Let’s use the case study below to illustrate. Code:
Production 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})
Explanation: The preceding code uses the open() function to create a new file named “Game.csv” with the write mode set to “w,” writes the data to that file using the DictWriter() function, and then specifies the column names as field names, which serve as the keys for the dictionary. The preceding output demonstrates the process of creating and saving a file.