Page 202 - Ai_V3.0_c11_flipbook
P. 202

• •    Writing rows to a CSV file: You can use the writerows() method to write multiple rows to a CSV file at once.
                  Each row should be a list of values. This function will replace all existing data in the CSV file.

                   Program 27: To write data to a CSV file row by row

                  import csv
                  # Open the CSV file in write mode
                  with open("Customer.csv", mode='w', newline='') as file:
                      writer = csv.writer(file)

                      # Write the header row
                      writer.writerow(["Customer_ID", "First_Name", "Last_Name", "City"])
                      while True:
                          # Accept customer details from the user

                          C_ID = input("Enter the Customer ID (or type 'exit' to finish): ")
                          if C_ID.lower() == 'exit':
                              break
                          Fname = input("Enter first name: ")
                          Lname = input("Enter last name: ")

                          City_Name = input("Enter city: ")
                          # Write the customer details to the CSV file
                          writer.writerow([C_ID, Fname, Lname, City_Name])
                  Output:

                  Enter the Customer ID (or type 'exit' to finish): 1
                  Enter first name: Aishwarya
                  Enter last name: Iyer
                  Enter city: Chennai
                  Enter the Customer ID (or type 'exit' to finish): 2
                  Enter first name: Rajesh
                  Enter last name: Reddy
                  Enter city: Hyderabad
                  Enter the Customer ID (or type 'exit' to finish): exit
               • •    Append rows to a CSV file: Appending a row to an existing CSV file involves opening the file in append mode
                  (‘a’), and writing a single row of data to it. You can achieve this using the csv.writer object’s writerow() method.

                   Program 28: To write multiple rows in one go to a CSV file.

                  import csv
                  data =[['3', 'Sneha', 'Gupta', 'Kolkata'], ['4', 'Neha', 'Trivedi', 'Ahmedabad'],
                  ['5', 'Rahul', 'Mehta', 'Bangalore']]

                  with open('Customer.csv', 'a', newline='') as file:
                        writer = csv.writer(file)
                        writer.writerows(data)




                    200     Touchpad Artificial Intelligence (Ver. 3.0)-XI
   197   198   199   200   201   202   203   204   205   206   207