Saving a CSV File in Python
CSV is a Comma Separated Values files are most widely utilized for putting tabular data. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. Python has built-in module called csv
to write and Save a CSV File.
To save a CSV File:
- First, we need to import csv library.
- Then open the file as we usually do but instead of writing content on the read_file object, we create a new object called read_writer.
- This object provides us with the writelines() method which allows us to place all the row’s data within the enter one go.
Example:
# Python program to demonstrate # writing to CSV import csv # field names fields = [ 'Name' , 'Branch' , 'Year' , 'CGPA' ] # data rows of csv file rows = [ [ 'Nikhil' , 'COE' , '2' , '9.0' ], [ 'Sanchit' , 'COE' , '2' , '9.1' ], [ 'Aditya' , 'IT' , '2' , '9.3' ], [ 'Sagar' , 'SE' , '1' , '9.5' ], [ 'Prateek' , 'MCE' , '3' , '7.8' ], [ 'Sahil' , 'EP' , '2' , '9.1' ]] # name of csv file filename = "university_records.csv" # writing to csv file with open (filename, 'w' ) as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) # writing the data rows csvwriter.writerows(rows) |
Output:
Note: For more information, refer to Writing CSV files in Python.
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats.