Writing data

The write command only accepts one string at a time. So if you have several pieces of data, you’ll need to either join them together using concatenation or use multiple write commands.

Single command

  1. file.write( name + “,” + str(score) )

Multiple commands

  1. file.write(name)
  2. file.write(“,”)
  3. file.write(str(score))
def write_data(name, score):
    file = open("answer.txt", "w")
    file.write(name + " has the high score of " + str(score))
    file.close()
def write_data(name, score):
    file = open("answer.txt", "w")
    file.write(name)
    file.write(" has the high score of ")
    file.write(str(score))
    file.close()
# Each element on new line
def write_data(array): 
    file = open("answer.txt", "w")
    for i in range(len(array)):
        file.write(array[i])
        file.write("\n")
    file.close()
# Each line has the corresponding element from each array seperated by a comma
# array1[i],array2[i]
def write_data(array1, array2):
    file = open("answer.csv", "w")
    for i in range(len(array1)):
        file.write(array1[i])
        file.write(",")
        file.write(array2[i])
        file.write("\n")
    file.close()
def write_data(array):
    file = open("answer.csv", "w")
    for i in range(len(array)):
        file.write(array[i].name)
        file.write(",")
        file.write(str(array[i].age))
        file.write("\n")
    file.close()