python - 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()
解决方案
如果我理解正确,下面的内容可能会起作用。
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
推荐阅读
- hadoop - 无法在具有转义字符的配置单元中读取 JSON
- typescript - 应用程序在 android 11 版本中仅在 ionic 中崩溃
- c++ - 我使用优先级队列解决了下面描述的问题并得到了解决方案,但这不是最佳的。有人可以帮助我更好的方法吗?
- math - 如何在不解密的情况下将非对称加密中的值相乘
- .net-5 - .NET 5 Web API Identity.User.Name 在同时使用 Windows 身份验证和匿名身份验证时为空
- python - 如何在python中将回溯消息打印到新行
- css - 我需要帮助使几个元素对我网站上的视口更具响应性。(CSS)
- postgresql - 在修饰符反对 JS 中使用关系映射
- amazon-web-services - AWS SAM - 在另一个 SAM 模板中部署新的 Lambda 函数时,有什么方法可以附加现有的 API 网关
- python - 部署后Django heroku编程错误数据库不存在