首页 > 解决方案 > Python CSV 解析和文件生成

问题描述

我有超过 500 个条目的 CSV,我正在尝试生成重定向文件。CSV 的格式为:

/contact,/contact-us,
/about,/about-us,

/contact 是URL,/contact-us 是URL。

所需 .htm 文件的格式为:

url = "/contact"
is_hidden = 0
==
<?php
function onStart(){return Redirect::to("/contact-us");}
?>
==

.htm 文件的文件名并不重要(可以是 1.htm、2.htm 等)。

几年来我没有真正接触过 Python,我不确定它是否是最佳选择,但从我一直在阅读的内容来看,它似乎是 CSV 解析的可靠选择。

任何帮助将不胜感激。

编辑:这是我到目前为止

import pip
import csv
with open('redirects.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
print 'url = "'+row[0]+'\nis_hidden = 0\n==\n\n<?php\nfunction onStart(){return Redirect::to("'+row[1]+'");}\n?>\n=='

这正好打印出我需要的东西。我只需要将每个条目放入一个 .htm 文件(自动递增的文件名)。

编辑#2:我用这段代码得到了我想要的东西:

import pip
import csv
count = 0
with open('redirects.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
count += 1
count_str = str(count)

file = open('redirects/'+count_str+'.htm', 'w')
file.write('url = "' + row[0] + '"\nis_hidden = 0\n==\n\n<?php\nfunction onStart(){return Redirect::to("' + row[1] + '");}\n?>\n==')
file.close()

标签: pythonhtmlcsv

解决方案


如果我理解正确,下面的内容可能会起作用。

directories = open('filename', 'r').read()
splitted = directories.split(",")
correctlyformatted = [x.strip() for x in splitted]

counter = 0
for i in correctlyformatted:
    f=open(str(counter) + '.html', 'w')
    f.writeLines([
    'url = "' + i + '"',
    'i.s_hidden = 0',
    '==', 
    '<?php', 
    'function onStart(){return Redirect::to("' + i +'");}', 
    '?>', '=='])
    counter += 1

推荐阅读