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

标签 python python-2.7 csv web-crawler export-to-csv

我试图弄清楚如何使用 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/

相关文章:

python - 是什么导致 Python "Interpreter not Initialized (version mismatch?)"错误?

python - 如何将 JSON 列表转换为 CSV 文件中的两个不同列?

sql-server - 如何在不渲染的情况下将 SSRS 报告直接导出到 csv

python - 使用 Python 获取文件的 mimetype

python - 保存混淆矩阵

java - 在 Java 中实现这种模式的最佳方法(内部的 Python 示例)?

Python:返回运行给定函数n次的函数

python - Elasticsearch-Python 2.7-为分析器配置索引

python - 理解一个 super 简单的函数输出

r - 读取大量数字时使用 fread(R 中的 data.table)的错误?