Python write csv file
A csv stands for "comma separated values", which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as spreadsheet or database in plain text and has a common format for data interchange. The csv file opens into the excel sheet, and the rows and columns data define the standard format.
Python CSV Module Functions
The CSV module work is to handle the CSV files to read/write and get data from specified columns. There are different types of CSV functions, which are as follows:
Writing csv files
We can also write any new and existing csv files in Python by using csv.writer() module. It is similar to csv.reader() module and also has two methods, i.e. writer function or the Dict Writer class.
It presents two functions, i.e., writerow() and writerows(). The writerow() function only write one row and the writerows() function write more than one row.
It is defined as a construct that allows you to create, store, and re-use various formatting parameters. It supports the several attributes; the most frequently used are:
Let's write following data to a CSV File.
It returns the file named as 'Python.csv' that contains the following data:
Write a CSV into a Dictionary
We can also use the class DictWriter to write the csv file directly into a dictionary.
A file named as python.txt contains following data:
emp_name,dept,birth_month Parker,Accounting,November Smith,IT,October
Writing csv files using pandas
Pandas is defined as an open source library which is built on the top of NumPy library. It provides fast analysis, data cleaning and preparation of the data for the user.
It is as easy as reading the csv file using pandas. You need to create the DataFrame, which is a two-dimensional, heterogeneous tabular data structure and consists of three main components- data, columns, and rows.
Here, we take a slightly more complicated file to read, called hrdata.csv, which contains data of company employees.
Employee,Hired,Salary,Sick Days John Idle,2014-03-15,50000.0,10 Smith Gilliam,2015-06-01,65000.0,8 Parker Chapman,2014-05-12,45000.0,10 Jones Palin,2013-11-01,70000.0,3 Terry Gilliam,2014-08-12,48000.0,7 Michael Palin,2013-05-23,66000.0,8