Using I a python script I am trying to make changes to a CSV file by changing strings to the integers via a key, ie Male = 0 and Female =1. However, when I write to the CSV with the first function and do it again with the second function, it will overwrite the changes I have already made. Solutions? Or is there a better way to read and write to a CSV file?
import csv
def category():
for line in csv_reader:
if line[1] == ("Male"):
line[1] = "0"
elif line[1] == ("Female"):
line[1] = "1"
csv_writer.writerow(line)
def pets():
for line in csv_reader:
if line[2] == ("Cat"):
line[2] = "0"
elif line[2] == ("Dog"):
line[2] = "1"
else: line[2] = "2"
csv_writer.writerow(line)
with open('information.csv', 'r', encoding = 'utf') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
with open('updated_version.csv', 'w', encoding ='utf-8', newline ='') as
new_file:
csv_writer = csv.writer(new_file)
for line in csv_reader:
category()
pets()