How to Write to a CSV File in Python
CSV files are widely used for data storage and exchange because of their simple, lightweight structure. CSV stands for Comma Separated Values, which means that data items are separated by commas.
Each line in a CSV file represents a row of data while the columns represent the fields. CSV files can be opened and edited in any text editor, and can easily be parsed and manipulated by programming languages like Python.
Benefits of using CSV Files
One of the main benefits of using CSV files is their flexibility. They can be easily generated and read by different software applications and programming languages. CSV files are universal, so they can be used in a great variety of scenarios, from simple data exchange between different software to complex data manipulation and analysis.
Steps to Write to a CSV File in Python
To write data to a CSV file in Python, follow these steps:
1. Import the CSV module
To start using the module, we first need to import it in our Python script.
2. Creating and opening a CSV file
Create a new CSV file and open it using the open() method.
3. Writing data to the CSV file
We can write data to the CSV file either by writing it row by row or by writing it as a list or dictionary.
4. Closing the CSV file
After writing the data, it is important to close the file to free up system resources.
How to write to a csv file using csv.writer in Python
You can create and write into the file with the following lines of code:
import csv
Columns = ['Team', 'Number_of_wins', 'Runner_Ups']
rows = [ ['Brazil', '5', '2'],
['Germany', '4', '4'],
['Italy', '4', '2']]
with open('fifawc.csv', 'w') as f:
write = csv.writer(f)
write.writerow(Columns)
write.writerows(rows)
The following has been completed:
- We have imported Python’s csv module
- Defined columns list with column names and rows list with the values
- Then opened file with the filename in the parameter along with write mode
- Assigned writer object in the write. It contains the filename alias to write the lists into the spreadsheet.
- The writer method will create a csv file
- Finally, we wrote in the datasheet.
writerow adds a single row and writerows adds multiple rows in to the tabular data
Syntax: csv.writer(csvfileObject, dialect=’excel’, **fmtparams)
Parameters
csvfileObject a csv file you want to create
dialect object in which you pass a set of parameters
fmtparams a keyword argument to override dialect argument
How to write to a csv file using csv. DictWriter in Python
DictWriter is another class of csv modules to deal with the tabular data files. Dictwriter writes the Dictionary objects into comma separated values file.
Syntax csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
Methods
Writeheader writes first rows provided in a one-dimensional dictionary.
writerows(dict_A) writes multiple rows by taking a dictionary object.
See the following code:
import csv
# my data rows as dictionary objects
Record_dict =[{'dept': 'CS', 'cgpa': '3.0', 'Sname': 'Akhter'},
{'dept': 'BEE', 'cgpa': '3.1', 'Sname': 'Hafeez'},
{'dept': 'CS', 'cgpa': '3.3', 'Sname': 'Hamza'},
{'dept': 'Maths', 'cgpa': '2.9', 'Sname': 'Danish'},
{'dept': 'BBA', 'cgpa': '3.8', 'Sname': 'Bilal'},
{'dept': 'SE', 'cgpa': '2.8', 'Sname': 'Younus'}]
fields = ['Sname', 'dept', 'cgpa']
filename = "university_records.csv"
with open(filename, 'w') as csvfile:
Writer = csv.DictWriter(csvfile, fieldnames = fields)
Writer.writeheader()
Writer.writerows(Record_dict)
Writing Data to a CSV File in Python
Python’s CSV module provides various methods for writing data to a CSV file. Here are some of the methods:
1. Writing data in rows and columns using CSV writer module
This method involves creating a writer object and writing rows and columns to the CSV file.
2. Writing data from a list to a CSV file
To write data from a list to a CSV file, we simply need to create a writer object and write the list to the CSV file.
3. Writing data from a dictionary to a CSV file
To write data from a dictionary to a CSV file, we can use the DictWriter object provided by the CSV module.
Reading Data from a CSV File in Python
Python’s CSV module also provides various methods for reading data from a CSV file. Here are some of the methods:
1. Importing the CSV module
To start reading data from a CSV file, we first need to import the CSV module in our Python script.
2. Opening and reading the CSV file
We can open the CSV file and read its contents using the open() method.
3. Parsing the CSV file data
Once we have opened the CSV file, we can parse the data using the DictReader or the reader method provided by the CSV module.
Conclusion
In summary, CSV files are widely used for data storage and exchange because of their simplicity and flexibility. In Python, we can easily read from and write to CSV files using the CSV module.
By following the steps outlined above, you can manipulate CSV files with ease. Additionally, there are many resources and references available to further your understanding of CSV file handling in Python.