import urllib
import csv
@manager.command
def list_routes():
for rule in app.url_map.iter_rules():
options = {}
for arg in rule.arguments:
options[arg] = "[{0}]".format(arg)
url = rule.rule
line = urllib.parse.unquote("{}{} ".format(rule.endpoint, url))
with open('urls.cvs', 'a') as out:
spamwriter = csv.writer(out, lineterminator='', dialect='excel')
spamwriter.writerows(line)
spamwriter.writerows('\n')
我需要填写csv文件,以便rule.endpoint和url具有单独的列。
答案 0 :(得分:3)
您的writerows
参数只需要是该行应包含的值列表的列表。因此,例如writer.writerows([[1, 2], [3, 4]])
将添加两行,其中每行包含两个值。当您只添加一行时,可以使用writerow
:
spamwriter.writerow([rule.endpoint, url])
这是一个模型。我使用BytesIO
,因此我不需要实际写入文件:
import csv
import io
c = io.BytesIO()
w = csv.writer(c, lineterminator="", dialect="excel")
w.writerow(['endpoint', 'url'])
print(c.getvalue()) # prints: endpoint,url
答案 1 :(得分:0)
import csv
@manager.command
def list_routes():
with open('urls.csv', 'w') as out:
csv_writer = csv.writer(out, lineterminator='\n')
csv_writer.writerows([[rule.endpoint, rule.rule] for rule in app.url_map.iter_rules()])