0

I'm very new to Python and I have this CSV file.

The File I'm working with

I need to add ten dollars to the accounts. Their balances I need to add to are in column D. How do I do that.

pandas is unavailable to me.

Then I need to save it to a different file with a different name.

flaxel
  • 4,173
  • 4
  • 17
  • 30
Dr. DT
  • 1
  • does this question answer your question :https://stackoverflow.com/questions/55404141/read-a-csv-file-and-perform-data-analysis-without-using-any-libraries-like-numpy – Rajat Mishra Dec 04 '20 at 00:26
  • Use csv module to read and write the files. Read one line at a time into a list. Add 10 to the ‘column index’ of the list. Write the updated list to an output file using the csv module. – Blake G Dec 04 '20 at 03:25

1 Answers1

0
import csv

# read rows
rows = []
with open('file.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')
    for row in reader:
        rows.append(row)

# add the value
for row in rows:
    row["Balance"] = float(row["Balance"]) + 10

# write csv back
with open("new.csv", "w", newline='') as outfile:
    writer = csv.DictWriter(outfile, fieldnames=list(rows[0]))
    writer.writeheader()
    writer.writerows(rows)

I am also adding pandas way, maybe you use it later.

import pandas as pd
df = pd.read_csv("file.csv", index_col=0, delimiter = ",")
df["Balance"] += 10
df.to_csv("new.csv", sep=',')
can
  • 309
  • 1
  • 4
  • 13