Home > Enterprise >  Match IDs with fruits from CSV files in Python
Match IDs with fruits from CSV files in Python

Time:10-01

I have hit some problems while making a program that matches some ids with some objects (In this case fruits) from CSV files.

The Python code :

import csv

#Opens users fruits and CSV with ids and fruits
usersFruit = open("list_of_users_fruits.csv",encoding="utf-8")
ids = open("list_of_fruit_ids.csv",encoding="utf-8")

def find_id(fruits):
    #reads the csv and splits the fruits and ids
    reader = csv.reader(ids, delimiter=';')
    fruits = usersFruit.readlines()

    #for loop for splitting up the users fruits into rows
    for fruit_name in fruits:
        print(fruit_name)
        for row in reader:
            if fruit_name.lower() in row[1].lower():
                print(row[0]  " "  fruit_name)

find_id(usersFruit)

CSV file with the usersFruit (Example):

Apple
Banana
Orange
Tomato

CSV file with the ids (minimized example) :

123;Apple
420;Banana
69430;Orange
314;Tomato

It should output something like this

123 Apple
420 Banana
69430 Orange
314 Tomato

But rn it outputs this

Apple

Banana

Orange

Tomato

If anybody knows how to output the desired please help, because I'm pretty stuck and it's a good time ago I last coded something, and I really need some guidance on this one. :D

Hopefully thanks in advance

Mikkel

CodePudding user response:

I'm confused by why you want to compare the two files when the list_of_fruit_ids.csv has the ID and the fruit name together? Can you just split the resulting list from "reader"? One of the problems with your original code is that you aren't putting both the usersFruit and ids CSVs into the find_id function -> def find_ids(ids, fruits) instead of def find_ids(ids). The function isn't even seeing the other file at all because of this.

I've included a simplified version of the code, but if you still need it to do the comparison that you're trying to do, then just make sure to add the correct parameters and arguments like I mentioned above. I can update this if you need me to show that if what I put below isn't sufficient.

import csv

# Opens CSV with ids and fruits
ids = open("list_of_fruit_ids.csv", mode='r', encoding="utf-8-sig")


def find_id(ids):
    reader = csv.reader(ids, delimiter=';')
    for row in reader:
        print(f"{row[0]} {row[1]}")

find_id(ids)

CodePudding user response:

csv.reader returns an iterator. After you iterate the entire list, it becomes empty. Convert the csv.reader as a list to iterate it repeatedly. In your case, simply add list() to your reader like:
reader = list(csv.reader(ids, delimiter=';'))

import csv

#Opens users fruits and CSV with ids and fruits
usersFruit = open("list_of_users_fruits.csv",encoding="utf-8")
ids = open("list_of_fruit_ids.csv",encoding="utf-8")

def find_id(fruits):
    #reads the csv and splits the fruits and ids
    reader = list(csv.reader(ids, delimiter=';'))
    fruits = usersFruit.readlines()

    #for loop for splitting up the users fruits into rows
    for fruit_name in fruits:
        fruit_name = fruit_name.strip()
        for row in reader:
            if fruit_name.lower() in row[1].lower():
                print(row[0]  " "  fruit_name)

find_id(usersFruit)

Now you get what you want:

123 Apple
420 Banana
69430 Orange
314 Tomato

CodePudding user response:

The first problem is that you're using .readlines() which includes newlines, which you don't want. You can use .read().splitlines() instead.

The next problem is that you don't reset your reader after each iteration so only the first fruit_name iteration will work (since the reader is at EOF). I'd use a context manager myself, but to make the least amount of changes to your code you can just send seek back to 0:

import csv

#Opens users fruits and CSV with ids and fruits
usersFruit = open("list_of_users_fruits.csv", encoding="utf-8")
ids = open("list_of_fruit_ids.csv", encoding="utf-8")


def find_id(fruits):
    #reads the csv and splits the fruits and ids
    reader = csv.reader(ids, delimiter=';')
    fruits = usersFruit.read().splitlines()

    #for loop for splitting up the users fruits into rows
    for fruit_name in fruits:
        for row in reader:
            if fruit_name.lower() == row[1].lower():
                print(row[0]   " "   fruit_name)

        ids.seek(0)


find_id(usersFruit)

Alternatively, like another user mentioned, you can convert reader to a list for evaluation.

  • Related