Python CSV module, add column to the side, not the bottom
Question: I am new in python, and I need some help. I made a python script that takes
two columns from a file and copies them into a "new file". However, every now
and then I need to add columns to the "new file". I need to add the columns on
the side, not the bottom. My script adds them to the bottom. Someone suggested
using CSV, and I read about it, but I can't make it in a way that it adds the
new column to the side of the previous columns. Any help is highly
appreciated.

Here is the code that I wrote:

    
    
    import sys
    import re
    
    filetoread = sys.argv[1]
    filetowrite = sys.argv[2]
    
    newfile = str(filetowrite) + ".txt"
    
    openold = open(filetoread,"r")
    opennew = open(newfile,"a")
    
    rline = openold.readlines()
    
    number = int(len(rline))
    start = 0
    
    for i in range (len(rline)) :
        if "2theta" in rline[i] :
            start = i
    
    for line in rline[start + 1 : number] :
        words = line.split()
        word1 = words[1]
        word2 = words[2]
        opennew.write (word1 + " " + word2 + "\n")
    
    openold.close()
    opennew.close()
    

Here is the second code I wrote, using CSV:

    
    
    import sys
    import re
    import csv
    
    filetoread = sys.argv[1]
    filetowrite = sys.argv[2]
    
    newfile = str(filetowrite) + ".txt"
    
    openold = open(filetoread,"r")
    
    rline = openold.readlines()
    
    number = int(len(rline))
    start = 0
    
    for i in range (len(rline)) :
        if "2theta" in rline[i] :
            start = i
    
    words1 = []
    words2 = []
    
    for line in rline[start + 1 : number] :
        words = line.split()
        word1 = words[1]
        word2 = words[2]
        words1.append([word1])
        words2.append([word2])
    
    with open(newfile, 'wb') as file:
        writer = csv.writer(file, delimiter= "\n")
        writer.writerow(words1)
        writer.writerow(words2)
    

These are some samples of input files:

  * <https://dl.dropbox.com/u/63216126/file5.txt>
  * <https://dl.dropbox.com/u/63216126/file6.txt>

My first script works "almost" great, except that it writes the new columns at
the bottom and I need them at side of the previous columns.


Answer: The proper way to use `writerow` is to give it a single list that contains the
data for _all_ the columns.

    
    
    words.append(word1)
    words.append(word2)
    writer.writerow(words)
    

