Let's consider a scenario where we are reading data from different sensors. This data needs to be recorded to a CSV file where each column corresponds to a reading from a specific sensor. We are going to discuss an example where we record the value 123, 456, and 789 in the first row of the CSV file and the second row is going to consist of values including Red, Green, and Blue:
- The first step in writing to a CSV file is opening a CSV file using the with keyword:
with open("csv_example.csv", 'w') as csv_file:
- The next step is initializing an instance of the writer class of the CSV module:
csv_writer = csv.writer(csv_file)
- Now, each row is added to the file by creating a list that contains all the elements that need to be added to a row. For example: The first row can be added to the list as follows:
csv_writer.writerow([123, 456, 789])
- Putting it altogether, we have:
import csv
if __name__ == "__main__":
# initialize csv writer
with open("csv_example.csv", 'w') as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow([123, 456, 789])
csv_writer.writerow(["Red", "Green", "Blue"])
- When the above code snippet is executed (available for download as csv_write.py along with this chapter), a CSV file is created in the local directory with the following contents:
123,456,789
Red,Green,Blue