Python readlines() 并将数据附加到每一行输出到一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22136173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python readlines() and append data to each line output to one line
提问by Matt
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()
采纳答案by Joel Cornett
That's because each linein 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 writeing to f_out:
那是因为每个lineinf_in.readlines()都在末尾添加了一个换行符。(尝试print(repr(line))在该循环中添加一个)。您需要做的是在writeing 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 withstatements take care of closeing files, so you don't need those last two lines.
这些with语句处理closeing 文件,因此您不需要最后两行。
UPDATE
更新
As J.F. Sebastian pointed out, it's also necessary to slugifythe city name to achieve the output you want.
正如 JF Sebastian 指出的那样,还需要对城市名称进行slugify以实现您想要的输出。
回答by Nayeem Zen
Try the python CSV modulefor 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)

