如何使用 python 2.7 导出带标题的 CSV 文件

问题描述 投票:0回答:1

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

第一列应包含 URL 结果,我想为此列命名。第二列应包含

print
结果
keyword found
keyword NOT found
(如我的代码中的第一个和第二个
print
函数所示)。我也想命名第二列。

我的代码:

import urllib2
    
keyword = ['viewport']

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():
                        print (strdomain, keyword, 'keyword found')

                    else:
                        print (strdomain, 'keyword NOT found')

            except urllib2.HTTPError:
                print (strdomain,'HTTP ERROR')

            except urllib2.URLError:
                print (strdomain,'URL ERROR')

            except urllib2.socket.error:
                print (strdomain,'SOCKET ERROR')

            except urllib2.ssl.CertificateError:
                print (strdomain,'SSL Certificate ERROR')

f.close()

那么我需要添加什么样的代码才能实现我的目标?

python python-2.7 csv web-crawler export-to-csv
1个回答
2
投票

您可以使用

','.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')
© www.soinside.com 2019 - 2024. All rights reserved.