I'm trying to find a way to take data in a csv file and run it through a loop to create output for each row. For example, this csv file has 4 columns titled name, color, age, gender. I wrote this code to try and accomplish that.
csv_file = input("Enter the location of your file. ")
with open(csv_file, 'r') as cat_example:
cat_entries = csv.DictReader(cat_example)
name = []
color = []
age = []
gender = []
for col in cat_entries:
name.append(col["name"])
color.append(col["color"])
age.append(col["age"])
gender.append(col["gender"])
with open("cat_output_file.txt","w") as f:
i = 0
for (name,color,age,gender) in zip(name,color,age,gender):
while i < 10:
f.write(f"This cat's name is {name}, fur color is {color}, its age is {age} and its gender is {gender}.""\n")
i = i 1
f.close()
I am trying to get the output to be the following.
This cat's name is Bob, fur color is orange, its age is 4, and its gender is male.
This cat's name is Tina, fur color is black, its age is 2, and its gender is female.
This cat's name is Frank, fur color is white, its age is 6, and its gender is male.
This cat's name is Samantha, fur color is purple, its age is 43, and its gender is female.
But instead I'm getting this output, just the first row repeated 4
This cat's name is Bob, fur color is orange, its age is 4, and its gender is male.
This cat's name is Bob, fur color is orange, its age is 4, and its gender is male.
This cat's name is Bob, fur color is orange, its age is 4, and its gender is male.
This cat's name is Bob, fur color is orange, its age is 4, and its gender is male.
How would I best be able to get the results I'm looking for? I tried doing a 'pop' in the f-string, but that didn't work.
I really appreciate any help!
CodePudding user response:
I think this should help, you didn't require the While loop, which was causing the repetition of results
with open(csv_file, 'r') as cat_example:
cat_entries = csv.DictReader(cat_example)
name = []
color = []
age = []
gender = []
for col in cat_entries:
name.append(col["name"])
color.append(col["color"])
age.append(col["age"])
gender.append(col["gender"])
with open("cat_output_file.txt","w") as f:
for (name,color,age,gender) in zip(name,color,age,gender):
f.write(f"This cat's name is {name}, fur color is {color}, its age is {age} and its gender is {gender}.""\n")
f.close()