Python

Python Read CSV Tutorial

CSV stands for ‘Comma Separated Values’. It is the simplest way to store the data as a plain text. Data is in the tabular form, each line is the row of the table record. In this guide you will view how to read a CSV file with different functions and also how to create a CSV file.

Prerequisite

To understand the methodology of a CSV file, you need to install a python running tool that is spyder. Also, you have python configured on your machine.

Method 1: Use csv.reader() to Read a csv File

Example1: Using a comma delimiter, read a file

Consider a file named ’sample1’ having the following data in it. The file can be created directly by using any text editor or by riding values using a specific source code to write a CSV file. This creation is debated further in the article. The text in this file is parted by a comma. The data belongs to the book information having the book name and the author name.

To read the file, following code will be used. To read a CSV file, we need to have a reader object to execute the reader function. The first step in this function is to import the CSV module, which is the built-in module, to use it in python language. In the second step, we provide the file name or a path of the file which is to be opened. Then initialize the CSV reader object. This object iterate according to the FOR loop.

$ Reader = csv.reader(file)

The data is printed as an output row-wise from the given data.

After writing the code, it’s time to execute it. You can view the output in the right side window on the screen in the Spyder. Here, you can see that your data is automatically organized with square brackets and single quotes.

Example 2: Using a tab delimiter, read a file

In the first example, the text is parted by a comma. We can make our code more customizable by adding different functionalities. For instance, you can see in this example we have used the tab option to remove extra spaces caused by using the ‘tab’. There is only a single change in the code. We have defined the delimiter here. In the previous example, we felt no need of defining the delimiter. The reason behind this is, the code considers it as a comma by default. ‘\t’ act for the tab.

$ Reader = csv.reader(file, delimiter = ‘\t’)

You can see the functionality in the output.

Method 2:

Now, we are going to discuss the second method of reading CSV files. Let’s suppose we have a file sample5.csv saved with the extension of .csv. Data present inside the file is as follows. This example contains the data of students having their name, class, and subject name.

Now, moving towards the code. The first step is the same as that is of importing the module. The path or name of the file which needed to be open and used is then provided. This code is an example of reading and altering the data at the same time. We have initiated two arrays for future usage in this code. Then we will open the file by using the open function. Then initialize the object as we have done so in the above examples. Here again, the FOR loop is used. The object iterate every time. The next function stores the current value of the rows and forwards the object for the next iteration.

$ Fields = next(csvreader)

$ Rows.append(row)

All the rows are appended to the list named ’rows’. If we want to see the total number of rows then we will call the following print function.

$ Print(“total rows are: %d “%(csvreader.line_num)

Then, to print the column’s heading or fields name, we will use the following function in which text is attached with all the headings using the “join” method.
After execution, you can see the output in which each row is printed with the whole description and the text we have added through the code at the time of execution.

Python Dictionary Reader Dict.reader

This function is also used to print the dictionary from the text file. We have a file having the following data of the students in the file named ‘sample7.txt’. It’s not necessary to save the file in only the .csv extension, we can also save the file in other formats if the simple text is used so that the data remain intact.

Now, we will use the below affixed code to read the data and print it in the dictionary format. All methodology is the same, only in the place of a reader, dictreader is used.

$ Csv_file = csv.DictReader(file)

While execution, you can see the output in the console bar that the data is printed in the form of a dictionary. The given function converts each row to a dictionary.

Initial Spaces and CSV File

Whenever the csv.reader() is used, we automatically get the spaces in the output. To remove these extra spaces from the output we need to use this function in our source code. Suppose a file having the following data regarding an employee’s information.

$ Reader =csv.reader(file, skipinitialspace = True)

The skipinitialspace is initialized with true so that the unused free space is removed from the output.

CSV Module and the Dialects

If we start to work by using the same csv files with function formats in the code, this will make the code very ugly and will lose concurrency. CSV helps in using the dialects method as an option to remove the redundancy of the data. Let us consider the same file as an example having the symbol “|” in it. We want to remove this symbol, skip extra space, and use single quotes among the respective data. So the following code will be entertain.

By using the appended code, we will get the desired output

$ Csv.register_dialect(‘myDialect’ , delimiter =’|’ ,skipinitialspace =True, quoting= csv.QUOATE_ALL)

This line is different in code as it defines three main functions to be performed. From the output, you can see that the symbol ‘|; is removed and single quotes are also added.

Write a CSV File

To open a file, there must be already a csv file present. If it is not, then we need to create it by using the following function. The steps are the same as we first import the csv module. Then we name the file that we want to create. To add data, we will use the following code:

$ Writer = csv.writer(file)
$ Writer.writerow(……)

The data is entered in the file row-wise, hence this statement is used.

Conclusion

This article will teach you how to create and read a csv file with alternate methods and in the form of dictionaries or to remove extra spaces and special characters from the data.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.