0

I'm trying to build a csv file one row at a time by appending to an existing file in a loop. I also want to have column headers at the top of the file. Is there a way to have the headers while building the file by appending.

This is my code:

while True:
  try:
    print("What class are you from? Between 1 to 3. ") # this is deciding which class the user is from
    Class = int(input()) #depending on the input, it goes to the correct class files to be stored as a CSV file
    if Class == 1:
        with open('Class 1.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #this is for writing the headers
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break #this is to get out of the loop
    elif Class == 2:
        with open('Class 2.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break
    elif Class == 3:
        with open('Class 3.csv', 'a') as csvfile:
            fieldnames = ['Name', 'Score']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerow({'Name': name, 'Score': score})
        break
    else:
        print("Please enter a number between 1 to 3.") #this loops if the user inputs a number too high
  except ValueError:
    print("Please enter a number between 1 to 3.")
DavidW
  • 29,336
  • 6
  • 55
  • 86
  • How many rows each of the files should have? You seem to only write one line. You could have an easier time if you defined a function like `def writeForClass(class_number)` instead of copy-pasting your code. – 9000 Apr 23 '15 at 18:14
  • Could you clarify what your code actually does compared to what you want it to do? It isn't clear right now. Also, I can't see "append" in your code - how is append involved in this? – DavidW Apr 23 '15 at 18:15
  • What I want it do is to keep on having relying on user-input so that data is built overtime as the program gets reused over and over. – Carlo Sapin Apr 23 '15 at 18:22
  • @DavidW the "append" is at the ` with open('Class 1.csv', 'a') as csvfile:` or is that not the proper use of `append`, if at all "append" – Carlo Sapin Apr 23 '15 at 18:27
  • OK I understand. As you say, the "a" flag to `open` does open the file in append mode. – DavidW Apr 23 '15 at 18:29
  • Phew! I thought I was being mistaking my terminologies. – Carlo Sapin Apr 23 '15 at 18:31
  • I've had a go at editing the question to try to make it a bit clearer (it won't show up immediately though...). If I've misunderstood then please revert my edit! (Also, If I've misunderstood then my answer will also be useless.) – DavidW Apr 23 '15 at 18:49

2 Answers2

0

Basically you can write something to the CSV file before you started to call writeheader() / writerow().

fieldnames = ['Name', 'Score']
with open('Class %d.csv' % class_number, 'a') as csvfile:
   csvfile.write('; This is a comment in the first line\n')
   writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
   writer.writeheader()
   ...

Note that comments are not well-standardized in CSV. Semicolon as first character is usually understood.

Community
  • 1
  • 1
9000
  • 39,899
  • 9
  • 66
  • 104
0

I believe you're trying to ensure that the header only gets written once (at the top of the file), and a row gets added each iteration of the loop. I'd do something like this:

while True:
  # "try" removed to keep this short - you can re-add it as you like
  print("What class are you from? Between 1 to 3. ") # this is deciding which class the user is from
  Class = int(input()) #depending on the input, it goes to the correct class files to be stored as a CSV file
  if Class == 1:
    filename = 'Class 1.csv'
  elif Class == 2:
    filename = # ... implement this, and class 3 etc

  file_exists = os.path.exists(filename) # check to see if the file has already been started (you'll need to import os.path too)

  with open(filename, 'a') as csvfile:
    fieldnames = ['Name', 'Score']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    if not file_exists:
      # only write the header if we've just created the file
      writer.writeheader()
    # but write the row every time
    writer.writerow({'Name': name, 'Score': score})

The basic idea is that you check to see if the file already exists before you open it. If it doesn't you write the header. If it does exist you just write the row.

However - I'd personally try to go for a solution where you create a variable that tracks what will go in the csv file as the program runs, but only actually writes it out to the file when everything's finished. It will probably end up being simpler than appending to a file as you go.

DavidW
  • 29,336
  • 6
  • 55
  • 86