Search code examples
pythonloopscsvwhile-loop

How can I put more than one row in this csv code


import csv

name = input("name: ")
Number1 = input("number1: ")
Number2 = input("number2: ")
local = input("local: ")
continue = input("continue? Y/N: ")
while(continue == ""):
    Name = input("nome: ")
    number1 = input("Inscrição: ")
    Number2 = input("Seção: ")
    local = input("local: ")
    continue = input("continuar? S/N: ")
    v =  open("valores", "w")
    writer = csv.writer(v)
    writer.writerow([Name, number1, number2, local])
    
else:
    print("ok")

I'm trying to get the variables to be written in sequence in a csv file but when I run it it only writes one line, and keeps deleting and rewriting it (I want it to be in a loop until "continuar" == N like

Name: asdjhagsdjh
number1: kasjhdkhasdkl
Number2: sajfdksdh
local: asjfkjfhsdkj
continue? Y/N: Y
      (asdjhagsdjh,kasjhdkhasdkl,sajfdksdh,asjfkjfhsdkj)
Name: asdjhagsdjh
Number1: kasjhdkhasdkl
Number2: sajfdksdh
local: asjfkjfhsdkj
continue? Y/N: N
      (asdjhagsdjh,kasjhdkhasdkl,sajfdksdh,asjfkjfhsdkj
       asdjhagsdjh,kasjhdkhasdkl,sajfdksdh,asjfkjfhsdkj)

I'm starting now so if it's something stupid: I'm sorry


Solution

  • Writing ('w') erases the existing file each time it is opened. If you don't want that, use 'a' (append). You may want to add code to clear the file if it already exists, but I will leave that as an exercise:

    import csv
    
    # Open the file once, all writes will be to the end of the file.
    # 'with' will close the file when its block exits.
    with open('values.csv', 'a') as v:
        writer = csv.writer(v)
        continue_ = 'y'  # to enter the while loop, assume y for first pass
        while continue_.lower().startswith('y'):  # handles Y, Yes, YES, yes, y, yeppers, etc.
            name = input('Name: ')
            registration = input('Registration: ')
            section = input('Section: ')
            location = input('Location: ')
            writer.writerow([name, registration, section, location])
            continue_ = input('Continue? Y/N: ')  # NOW ask to continue
        else:
            print('ok')