简体   繁体   English

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

[英]How to export a CSV file with a header using python 2.7

I'm trying to figure out how to export the results of my script to a CSV file with python 2.7. 我试图弄清楚如何使用python 2.7将脚本结果导出到CSV文件。 The CSV file should contain two columns: CSV文件应包含两列:

The first column should contain the URL results and I would like to give this column a name. 第一列应包含URL结果,我想给该列起一个名字。 The second column should contain the print result keyword found or keyword NOT found (as seen after the first and second print function in my code). 第二列应包含keyword foundprint结果keyword found或未keyword found keyword NOT found (在我的代码的第一个和第二个print功能之后可见)。 I would like to name the second column as well. 我也想命名第二列。

My code as of now: 截至目前我的代码:

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()

I'm getting IndentationError: unexpected unindent 我收到IndentationError: unexpected unindent

So what should I adjust to make this work? 那么我该如何调整才能使它正常工作?

You can use the ','.join() method to convert a list into a string with a comma separator. 您可以使用','.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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM