简体   繁体   English

Python readlines()并将数据附加到每一行输出到一行

[英]Python readlines() and append data to each line output to one line

I have a csv file with say 3 rows like this: 我有一个说3行的csv文件,像这样:

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. 这是我到目前为止的代码,它读取csv文件并输出,但是它创建不同的行,我只需要一行,而且我需要为超链接附加html代码。

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()

That's because each line in f_in.readlines() comes with a newline tacked on to the end. 这是因为f_in.readlines()每一linef_in.readlines()附加了换行符。 (Try adding a print(repr(line)) in that loop). (尝试在该循环中添加print(repr(line)) )。 What you need to do is remove that newline before write ing to f_out : 您需要做的是在write 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. with语句负责close文件,因此您不需要最后两行。

UPDATE 更新

As JF Sebastian pointed out, it's also necessary to slugify the city name to achieve the output you want. 正如塞巴斯蒂安(JF Sebastian)指出的那样,也有必要对城市名称加以sl贬 ,以实现所需的输出。

Try the python CSV module for handling CSV files 尝试使用python CSV模块处理CSV文件

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM