Python 3 - Concatenate 2 CSV files into 1 file

Discussion in 'App Development' started by OptionsOptionsOptions, Mar 17, 2020.

  1. Python 3 - Concatenate 2 CSV files into 1 file

    1.CSV


    1
    2
    3
    4

    2.CSV

    A
    B
    C
    D

    I want to concatenate/append the 2 files to one:

    Output.CSV

    1,A
    2,B
    3,C
    4,D

    I can't find the solution anywhere, all I got is:

    Output.CSV

    1
    2
    3
    4
    A
    B
    C
    D

    Does anyone know the solution? I am using import CSV

     
  2. probably something like:

    Code:
    f = open('Output.CSV','w')
    for a,b in zip(open('1.CSV'),open('2.CSV')):
        f.write(a+','+b)
    
     
  3. Thanks ..... I'm heading out and will give the code a try tonight.
     
  4. Thanks again, it works perfectly. I made a small change by adding: a = (a.rstrip('\n'))

    Code:
    f = open('Output.CSV','w')
    for a,b in zip(open('1.CSV'),open('2.CSV')):
        a = (a.rstrip('\n'))
        f.write(a+','+b)
    I stripped the newline character from the first CSV file because it was pushing the 2nd CSV files contents down a row.
     
    nooby_mcnoob likes this.
  5. For future work of this kind, consider importing into pandas and manipulating tables there (as dataframes). Lot of flexibility.
     
    trader99 and d08 like this.
  6. Code:
    pd.read_csv('a.csv').join(pd.read_csv('b.csv')).to_csv('c.csv', index=False, header=False)
    
     
    zoned_post_meridiem likes this.
  7. Look at this guy bringing in his fancy pandas.
     
  8. [​IMG]
     
  9. Hipster panda

    [​IMG]
     
  10. Something wrong with the DNS server network. I typed elitetrader.com into my browser, and appear to have got stackexchange.

    GAT
     
    #10     Mar 18, 2020
    Same Lazy Element and d08 like this.