Merge semicolon delimited txt file looping in directory
Question: Suppose I have many different text files from the same directory with the
content structure as shown below:

File a.txt:

    
    
    HEADER_X;HEADER_Y;HEADER_Z
    a_value;a_value;a_value
    a_value;a_value;a_value
    

File b.txt:

    
    
    HEADER_X;HEADER_Y;HEADER_Z
    b_value;b_value;b_value
    b_value;b_value;b_value
    

File c.txt:

    
    
    HEADER_X;HEADER_Y;HEADER_Z
    c_value;c_value;c_value
    c_value;c_value;c_value
    

File d.txt: ...

I'd like to merge all of the txt files into one, by appending the content of
each file to the final row of the each previous file. See below:

File combined.txt:

    
    
    HEADER_X;HEADER_Y;HEADER_Z
    a_value;a_value;a_value
    a_value;a_value;a_value
    b_value;b_value;b_value
    b_value;b_value;b_value
    c_value;c_value;c_value
    c_value;c_value;c_value
    ...
    

How can I do this in Python?

Assumptions: \- all txt files are located in the same folder \- all txt files
have same headers \- all txt files have same number of columns \- all txt
files have different number of rows


Answer: Use the [CSV Module](https://docs.python.org/2/library/csv.html). Something
like this:

    
    
    import csv
    with ('output.csv', 'ab') as output:
        writer = csv.writer(output, delimiter=";")
    
        with open('a.txt', 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=";")
            reader.readline() // this is to skip the header
            for row in spamreader:
                writer.writerow(row)
    

If you didn't want to harcode in every file (Say you have many more than
three) you could do:

    
    
    from os import listdir
    from os.path import isfile, join
    onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
        for aFile in onlyfiles:
            with open(aFile, 'rb') as csvfile:
            reader = csv.reader(csvfile, delimiter=";")
            reader.readline() // this is to skip the header
            for row in spamreader:
                writer.writerow(row)
    

