Creating a new list when a condition is met with a value pair and a list

Viewed 98

Very first question ever on here. I have tried to find a solution for about a week now but I'm finally down to having to ask. I'm open to suggestions for the title of this question also.

I'm using python3

I have a csv file (legend.csv) that contains 2 headers(keys), one for numbers and one for abbreviations.

Each abbr has a corresponding number and this is represented in the csv file.

I also have a list of names (list.txt), the first part of the names are usually an abbr of some sort.

The idea behind the program is: I want to analyze the csv file and add the number that corresponds to the abbr in the names from the list.txt. The output should be a new text file if possible.

example of list.txt:
    addg-stuff
    cbdd-stuff
    abc-stuff
    add-stuff

example of legend.csv:
    number,abbr
    0001,addg
    0002,cbdd
    0003,abc
    0004,add


example of desired output:
    0003-abc-stuff
    0001-addg-stuff
    0004-add-stuff
    0002-cbdd-stuff

the following finds the abbr but I'm stuck on how to add the corresponding number to the name. Easiest way to cross-reference a CSV file with a text file for common strings

The link above is where I found how to pull the matching strings but not sure where to go from here.

   import csv
   with open("legend.csv") as csvfile:
       reader = csv.reader(csvfile)
       searchstring = {row[1] for row in reader}
       num = {row[0] for row in reader}
   with open("list.txt") as txtfile:
       for names in txtfile:
           for i in searchstrings:
               if i in name:
                   matching = (name) #not sure where to go from here. If matching is printed, the names are found that contain the abbr.

Definitely new to this, just started messing with python for a month or so. Any help would be much appreciated, especially if you have any good resources for situations like this or python in general.

1 Answers
Related