hhppaarr
hhppaarr

Reputation: 49

How to write in an existing CSV file with data from another csv file?

Just a bit of context: I have two CSV files:

The first one which I will call the Statement

The second one the Big File

The Big File contains a lot of data including Order ID numbers that are in the Statement.

What I want to do is:

If the Order ID from the Statement matches the Order ID from the Big File, then write in Big File in the column Paid, at the row that contains the Order ID, "Yes".

So what I wrote was:

import pandas as pd

data1 = pd.read_csv('Big_File.csv')
data2 = pd.read_csv('Statement.csv')

df = pd.DataFrame(data1)

for i in range(len(data1['PO'])):
    for j in range(len(data2['PO'])):

        if data2['PO'][j] == data1['PO'][i]:

            data1['Supplier'][i] = 'SUP'

            data1['Paid'][i] = 'yes'

When I run the code, no error, but then I open the Big File to check if it worked and nothing changed.

I am new to writing and reading files in Python, can anyone give me some advice?

Thanks in advance.

Upvotes: 2

Views: 1102

Answers (1)

jchung
jchung

Reputation: 953

You still need to output the changes back into the CSV files.

What you've done so far is to read the data from the CSV files into dataframes in Python, located in memory. Then you change them up. But then you stopped. After your for loop, you should then output the changed data1 back to CSV. For example:

data1.to_csv('Big_File.csv')

Here are the docs on to_csv https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.DataFrame.to_csv.html

Upvotes: 1

Related Questions