简体   繁体   English

如何使用pandas和csv模块在python中的for循环后保存字符串输出?

[英]How save an string output after a for loop in python with pandas and csv modules?

I have the following for loop: 我有以下for循环:

    for titles in titles:
        title = titles.xpath("a/text()").extract()
        link = titles.xpath("a/@href").extract()
        print(title, link)

How can I dump the title and link into a formmated .csv file? 如何转储标题并将其链接到已格式化的.csv文件中?

You should use the python CSV module. 您应该使用python CSV模块。 Look here for more information: Writing List of Strings to Excel CSV File in Python . 在此处查找更多信息: 用Python将字符串列表写入Excel CSV文件

Here is an example for your problem: 这是您的问题的示例:

import csv
results = []

# your code... also add this to your for loop.
    results.append([title, link])

csv_file = open("csv_file.csv",'wb')
wr = csv.writer(csv_file)
for row in results:
    wr.writerow(row)

Something like this ( documentation ): 像这样( 文档 ):

...
doc_path = "path/to/doc.csv" # must exist, first folder on the place
                             # where you are running the script!
with open(doc_path, 'a') as doc:
    for entry in titles:
        title = entry.xpath("a/text()").extract()
        link  = entry.xpath("a/@href").extract()
        print(title, link)
        doc.write(str(title)+','+str(link)+'\n')

Use a csv writer . 使用csv编写器

Basic usage: 基本用法:

import csv
with open('file.csv') as f:
    writer = csv.writer(f)
    writer.writerow(["title", "link"])
result = []
for titles in titles:
    title = titles.xpath("a/text()").extract()
    link = titles.xpath("a/@href").extract()
    print(title, link)
    result += [title + ',' + link + '\n']

with open("result.csv" "w+") as f:
    f.writelines(result)

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

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