Loop creates unwanted duplicate
<p>I am trying to pull in data from an input file and iterate over a symbol file to create output for an output file but my code is creating an unwanted duplicate in the output file.  The input file is very big so I need to filter the input first before I reference it against the symbol (city/state) file to generate the output.</p>

<pre><code>i_file = ('InputFile.csv')
o_file = ('OutputFile.csv')
symbol_file = ('SymbolFile.csv')
City = 'Tampa'
State = 'FL'

with open(symbol_file, 'r') as symfile:
    with open(i_file, 'r') as infile:
        with open(o_file, 'w') as outfile:

            reader = csv.reader(infile)
            symbol = csv.reader(symfile)
            writer = csv.writer(outfile, delimiter = ',')

            for row in reader:
                if (row[2] == city and row[3] == state):

                   for line in symbol:
                        if (row[4] == line[0]):
                            nline = ([str(city)] + [str(line[3])])
                            writer.writerow(nline)
                    symfile.seek(0)
</code></pre>

<blockquote>
  <p>I only want one line for every line in the input file IF there is a matching line in the symbol file. </p>
</blockquote>

<p>Try it like this then:</p>

<pre><code>i_file = 'InputFile.csv'
o_file = 'OutputFile.csv'
symbol_file = 'SymbolFile.csv'

city = 'Tampa'
state = 'FL'

# load the symbols from the symbol file and store them in a dictionary
symbols = {}
with open(symbol_file, 'r') as symfile:
    for line in csv.reader(symfile):
        # key is line[0] which is the thing we match against
        # value is line[3] which appears to be the only thing of interest later
        symbols[line[0]] = line[3]

# now read the other files
with open(i_file, 'r') as infile, open(o_file, 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, delimiter = ',')

    for row in reader:
        # check if `row[4] in symbols`
        # which essentially checks whether row[4] is equal to a line[0] in the symbols file
        if row[2] == city and row[3] == state and row[4] in symbols:
            # get the symbol
            symbol = symbols[row[4]]

            # write output
            nline = [city, symbol]
            writer.writerow(nline)
</code></pre>

python python-3.x loops