0

I'm trying to edit a single row in a csv file. I've got a CSV file that looks like the bellow:

TYPE|FOOD TYPE|FEED TIME|WASH TIME

LION|MEAT|4H|1D

FOX|MEAT|5H|3D

HEN|SEED|6H|6D

FISH|PLANTS|7H|99D

I want to edit the row based on its TYPE. If the user wants to edit the FOX row they only need to type FOX when prompted. The issue I'm facing is that the I can't edit the file for some reason.

My code is bellow, I open the existing db, find the row in question, change it, then write it, along with the other rows, into a temp file that I can overwrite the original with.

def edit_animal_entry(type):
with open(animal_csv, 'r') as file_read:
 reader = csv.reader(file_read, delimiter="|")
with open(temp, 'w') as file_write:
 writer = csv.writer(file_write)
 for row in reader:
 print(f"{' | '.join(row)}")
 if row[0] == type:
 animal_type, animal_food, animal_feed, animal_wash = animal_inputs()
 writer.writerow([animal_type, animal_food, (animal_feed+"H"), (animal_wash+"D")])
 else:
 writer.writerow(row)
shutil.move(temp, animal_csv)
Paul
27.8k13 gold badges90 silver badges127 bronze badges
asked Feb 2, 2019 at 23:17

1 Answer 1

2

You've 'closed' the read file by stopping the with block before reading anything out of it. Therefore you aren't looping over your input file. A solution would be to open the input and the output file in the same with statement:

def edit_animal_entry(type):
 with open(animal_csv, 'r') as file_read, open(temp, 'w') as file_write:
 reader = csv.reader(file_read, delimiter="|")
 writer = csv.writer(file_write)
 for row in reader:
 print(f"{' | '.join(row)}")
 if row[0] == type:
 animal_type, animal_food, animal_feed, animal_wash = animal_inputs()
 writer.writerow([animal_type, animal_food, (animal_feed+"H"), (animal_wash+"D")])
 else:
 writer.writerow(row)
 shutil.move(temp, animal_csv)
answered Feb 2, 2019 at 23:22
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.