如何使用 python 2.7 导出带有 header 的 CSV 文件

How to export a CSV file with a header using python 2.7

我正在尝试弄清楚如何使用 python 2.7 将我的脚本结果导出到 CSV 文件。 CSV 文件应包含两列:

第一列应包含 URL 个结果,我想为该列命名。第二列应包含 print 结果 keyword foundkeyword NOT found(如我代码中第一个和第二个 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: unexpected unindent

那么我应该如何调整才能使这项工作正常进行?

您可以使用 ','.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')