Faster to add all items to an array then write the array to file, or faster to write the item to a file and then add to array one at a time?
Question: So right now I have this (in Python 2.7):

    
    
    if y == ports[0]:
       Array1.append(x)
     elif y == ports[1]:
       Array2.append(x)
     elif y == ports[2]:
       Array3.append(x)
     elif y == ports[3]:
       Array4.append(x)
     else:
       Array5.append(x)
    
    for x in Array1:
        target=open('Array1.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array1.csv\n"
    
    for x in Array2:
     target=open('Array2.csv', 'a')
     target.write(x + ",\n")
     target.close()
     print "Added IP address " + x + " to Array2.csv\n"
    
    for x in Array3:
     target=open('Array3.csv', 'a')
     target.write(x + ",\n")
     target.close()
     print "Added IP address " + x + " to Array3.csv\n"
    
    for x in Array4:
      target=open('Array4.csv', 'a')
      target.write(x + ",\n")
      target.close()
      print "Added IP address " + x + " to Array4.csv\n"
    
    for x in Array5:
      target=open('Array5.csv', 'a')
      target.write(x + ",\n")
      target.close()
      print "Added IP address " + x + " to Array5.csv\n"
    

Would the program finish quicker if I did:

    
    
    if y == ports[0]:
        Array1.append(x)
        target=open('Array1.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array1.csv\n"
    elif y == ports[1]:
        Array2.append(x)
        target=open('Array2.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array2.csv\n"
    elif y == ports[2]:
        Array3.append(x)
        target=open('Array3.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array3.csv\n"
    elif y == ports[3]:
        Array4.append(x)
        target=open('Array4.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array4.csv\n"
    else:
        Array5.append(x)
        target=open('Array5.csv', 'a')
        target.write(x + ",\n")
        target.close()
        print "Added IP address " + x + " to Array5.csv\n"
    

Or would I see any difference at all? Or perhaps there is a third way that is
quicker? Does it matter when the item is written to the list?


Answer: That probably barely matters. What’s more important is not constantly
reopening the file:

    
    
    with open('Array1.csv', 'a') as target:
        for x in Array1:
            target.write(x + ",\n")
            print "Added IP address " + x + " to Array1.csv\n"
    

Also, I don’t know if it applies here, but [the `csv`
module](http://docs.python.org/3/library/csv.html) _does_ exist.

