O'Reilly logo

Automate it! - Recipes to upskill your business by Chetan Giridhar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing data into CSV files

Again, for the recipes in this section, we don't need any new modules apart from the ones that are bundled with the Python installation, that is, the csv module.

How to do it...

  1. First, lets open a file in write mode and in text format. We create two Python lists that contain the data to be written into the CSV file. The following code will perform these operations:
            import csv 
            names = ["John", "Eve", "Fate", "Jadon"] 
            grades = ["C", "A+", "A", "B-"] 
            f = open("newlist.csv", 'wt') 
    
  2. Let's now add the data into the CSV file with the write() method, as follows:
            try: 
                writer = csv.writer(f) 
                writer.writerow( ('Sr.', 'Names', 'Grades') ) 
                for i in range(4): 
                    writer.writerow( (i+1, names[i], grades[i]) ) 
            finally: 
                f.close() 
    

    In the preceding ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required