Writing to CSV Files-Unwanted Blank Row in File

The below code does accept the user input and generates a correctly formatted CSV file except that an unwanted blank row is inserted between each valid row… Any suggestions for eliminating the generation of the blank rows would be appreciated.

import csv

with open('D:\\activityV3.csv','w+') as file:
    my_file = csv.writer(file)
    my_file.writerow(["Id","Activity","Description","Level"])
    NoOfActivities = int(input("Enter # of activities: "))
    for i in range(NoOfActivities):
        activityID = input("Activity " + str(i + 1) + " : ActivityID: ")
        activity = input("Activity " + str(i + 1) + " : Activity: ")
        desc = input("Activity " + str(i + 1) + " : Desc: ")
        level = input("Activity " + str(i + 1) + " : Level: ")
        my_file.writerow([activityID, activity, desc, level])

The csv itself writes a newline at the end of every line, so you need to disable newlines when opening the file for writing:

with open('D:\\activityV3.csv','w+', newline='') as file:

2 Likes

Thanks for the quick reply.