Question

I have a csv file with say 3 rows like this:

Dallas
Houston
Ft. Worth

What I want to do is be able to read those in and make links out of them but have all the lines output on one line. Example output would need to be like this:

<a href="/dallas/">Dallas</a> <a href="/houston/">Houston</a> <a href="/ft-worth/">Ft. Worth</a>

Here is the code I have thus far and it reads the csv file and outputs but it creates different rows, and I only want one row plus I need to append the html code for hyper links in.

f_in = open("data_files/states/major_cities.csv",'r')
for line in f_in.readlines():
    f_out.write(line.split(",")[0]+"")
f_in.close()
f_out.close()
Was it helpful?

Solution

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 closeing 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.

OTHER TIPS

Try the python CSV module for handling CSV files

import csv
file_out = open('file.txt','w')
with open('example.csv','rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        col=row[0]
        str="<a href=/" + col.strip().lower()
        str+= "/>" + col + "</a> "
        file_out.write(str)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top