That's because each line
in f_in.readlines()
comes with a newline tacked on to the end. (Try adding a print(repr(line))
in that loop). What you need to do is remove that newline before write
ing to f_out
:
for line in f_in.readlines():
actual_line = line.rstrip('\n')
Your entire code would look like this:
import re
with open('data_files/states/major_cities.csv') as f_in:
with open('output_file.csv', 'w') as f_out:
for line in f_in:
city = line.rstrip('\n')
f_out.write('<a href="/{}/">{}</a>'.format(
re.sub(r'\W+', '-', city.lower()),
city
))
The with
statements take care of close
ing files, so you don't need those last two lines.
UPDATE
As J.F. Sebastian pointed out, it's also necessary to slugify the city name to achieve the output you want.