0

Ok, so I'm searching for two list of keywords in a csv file and I'm trying to save them as two different documents.

Here is my script.

import csv

with open ("kijiji_db.csv", "r", encoding="utf-8") as file:
     file_reader = csv.reader(file)
     listOfKeyWords = [["universite de montreal", "udem", "udm"], ["mil"]]

     for keywords in listOfKeyWords:
        resultats = []
        for keyword in keywords:
          for row in file_reader:
            if (keyword.lower() in row[5].lower() or keyword.lower() in row[1].lower()) and [row[1], row[2], row[3], row[4], row[5], row[7], row[8], row[9]] not in resultats:
                #print ("trouvé:", keyword)
                resultats.append([row[1], row[2], row[3], row[4], row[5], row[7], row[8], row[9]])
        print(resultats)
        with open("resultats_" + keywords[0] + ".csv", "w", encoding="utf-8") as file:
            writer = csv.writer(file)
            writer.writerows(resultats)
file.close()

Everything seems to work except that the second set of words (ie: "mil") give me an empty result. Also, it creates the csv file, but it's also empty.

braX
  • 11,506
  • 5
  • 20
  • 33
  • On first glance, I can see that you are using the variable "file" for two different files. Thats most likely the reason why you dont get an outfile. – Brizar Mar 04 '20 at 14:47
  • 1
    People use the `with` construct specifically to avoid having to do `file.close()` manually, so the last line seems a little misplaced. – liborm Mar 04 '20 at 14:57

1 Answers1

0

I'm not sure, but I think the problem is very similar to this post: Why can't I call read() twice on an open file?. The problem here was that you could not read an open file twice, since the read cursor is left at the end of the document.

If I'm right you could either open the file inside of the for keywords in listOfKeyWords: loop or use something like file_reader.seek(0). I've never used seek(0) before, but since it is the accepted answer in the other stackoverflow post, i'll assume that is should work too.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
dylenv
  • 53
  • 4