1.4 CSV file in Python
v CSV file in python: -
- A CSV file in Python is a Comma-Separated Values file used to store tabular data in plain text format, where each line represents a row, and values in a row are separated by commas (,).
- Each row in the file corresponds to a record.
- Columns are separated by a delimiter (comma by default, but can be ;, \t, or others).
- CSV files are human-readable and can be opened in text editors, Excel, Google Sheets, etc.
- Python uses CSV module to read and write the CSV files.
1. Writing CSV files: -
- To write to a CS to write CSV file in Python, we use the csv.writer( ) method.
- The csv.writer( ) method returns a writer object that converts the user’s data into a delimited string.
- This string can later be used to write into CSV files using the writerow( ) method.
- The two methods for writing to CSV are:
writerow( ):
This method writes a single row at a time. Field row can be written using this
method.
writerows(
): This method is used to write multiple rows at a time. This can be used to
write row’s list.
Example: -
output: -
2. Reading CSV
files: -
- To read a CSV file, we use csv.reader( ) method.
- The reader class from CSV module is used for reading CSV files.
- The reader( ) method of CSV module returns the reader object that iterates throughout the lines in the specified CSV document.
- We should specify the mode as ‘r’.
Example: -
output: -