timotom
timotom

Reputation: 75

How to append from one csv file to another?

Tried different ways. The closest way that may fit my need is the following code:

   with open('list.csv', 'r') as reader, open('list-history.csv', 'a') as writer:
         for row in reader:
             writer.writerow(row)

I'm using 'a' and tried 'w' as well but no luck. The result is no output at all. Any suggestion, please? Thanks.

Upvotes: 1

Views: 687

Answers (2)

Hayat
Hayat

Reputation: 1639

If both the csv columns have same name. Python's pandas module can help.

Example Code snippet.

import pandas as pd

df1 = pd.read_csv("csv1.csv")
df2 = pd.read_csv("csv2.csv")

df1.append(df2, ignore_index=True)
df1.to_csv("new.csv",index=False)

Upvotes: 2

Alexandr Shurigin
Alexandr Shurigin

Reputation: 3981

I think there should be a error with a stacktrace.

Here: writer.writerow(row)

Normally open() returns file object which doesn't have .writerow() method, normally, you should use .write(buffer) method.

Example

with open('list.csv', 'r') as reader, open('list-history.csv', 'a') as writer:
    for row in reader:
        writer.write(row)

For me it works well with test csv files. But it doesn't merge them, just appends content of one file to another one.

Upvotes: 3

Related Questions