我试图弄清楚如何使用 python 2.7 将脚本的结果导出到 CSV 文件。 CSV 文件应包含两列:
第一列应包含 URL 结果,我想为此列命名。第二列应包含 print
结果 找到关键字
或 未找到关键字
(如第一个和第二个 print
之后所示) > 我的代码中的函数)。我也想命名第二列。
我现在的代码:
import urllib2
keyword = ['viewport']
with open('top1m-edited.csv', 'w') as f:
# Write out your column headers
f.write(','.join(['column1header', 'column2header']))
with open('top1m-edited.csv') as f:
for line in f:
strdomain = line.strip()
if '.nl' in strdomain:
try:
req = urllib2.Request(strdomain.strip())
response = urllib2.urlopen(req)
html_content = response.read()
for searchstring in keyword:
if searchstring.lower() in str(html_content).lower():
f.write(','.join([strdomain, 'keyword found']) + '\n')
else:
f.write(','.join([strdomain, 'keyword NOT found']) + '\n')
print (strdomain, 'keyword NOT found')
f.close()
我收到IndentationError:意外的未缩进
那么我应该如何调整才能使这项工作正常进行?
最佳答案
您可以使用','.join()
方法将列表转换为带有逗号分隔符的字符串。
with open('my_file.csv', 'w') as f:
# Write out your column headers
f.write(','.join(['column1header', 'column2header']))
# Replace your for loop with this to write to file instead of stdout
for searchstring in keyword:
if searchstring.lower() in str(html_content).lower():
f.write(','.join([strdomain, 'keyword found']) + '\n')
else:
f.write(','.join([strdomain, 'keyword NOT found']) + '\n')
print (strdomain, 'keyword NOT found')
关于python - 如何使用 python 2.7 导出带标题的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42425856/