保存到文件问题

时间:2017-03-21 05:08:05

标签: python beautifulsoup html-parsing

我正在尝试将生成的列表保存到文件中,我看到列表中的打印很好,但它不会写入compoundlist.csv文件。我不确定我做错了什么,我试图在列表生成后以及循环期间写入。我得到了相同的结果。

import urllib
import urllib.request
from bs4 import BeautifulSoup
import os
import csv


def make_soup(url):
    thepage = urllib.request.urlopen(url)
    soupdata = BeautifulSoup(thepage, "html.parser")
    return soupdata


compoundlist = []
soup = make_soup("http://www.genome.jp/dbget-bin/www_bget?ko00020")
i = 1
file = open("Compoundlist.csv", "wb")
for record in soup.findAll("nobr"):
    compound = ''
    if (record.text[0] == "C" and record.text[1] == '0') or (record.text[0] == "C" and record.text[1] == '1'):
        compoundlist = "http://www.genome.jp/dbget-bin/www_bget?cpd:" + record.text
        file.write(compoundlist)
        print(compoundlist)

1 个答案:

答案 0 :(得分:0)

尝试在代码末尾添加以下内容

file.close()

将打开的文件缓冲区刷新到文件