Python csv文件写空白?

时间:2017-03-18 22:59:30

标签: python csv

我看起来非常努力,仍然无法理解这里出了什么问题。我试图从网站中提取数据,但是当将数据写入csv文件时,即使代码看起来是正确的,也不会在文件中附加任何内容。有人可以解释为什么!! ??

import csv
import requests
from bs4 import BeautifulSoup

url = "https://en.wikipedia.org/wiki/List_of_countries_by_past_and_future_population#Sources"
r = requests.get(url)
soup = BeautifulSoup(r.content)
writer = csv.writer(open("/Users/alihamed/Desktop/PopulationsOfCountries.csv", 'w'))

data = []
with open('PopulationsOfCountries'+'.csv','w') as f:
    writer = csv.writer(f, delimiter =',')

    for tables in soup.findAll("table",{"class": "sortable wikitable"}):
        print("In!") 
        #writer.writerow(data)
        #f.flush()
        #writer.writerow(data)
        '''write table contents from here
           append newline
        '''
        for tr in tables.findAll("tr"):
           # data.append("\n")
            for td in tr.findAll("td"):               
                #print td.string                                    
                data.append(td.string)
                #writer.writerow(data)
                '''

                '''
            writer.writerow(data)   
            f.flush()            
    #print(data)         
f.close()

1 个答案:

答案 0 :(得分:1)

您打开两个文件对象:

writer = csv.writer(open("/Users/alihamed/Desktop/PopulationsOfCountries.csv", 'w'))

然后

with open('PopulationsOfCountries'+'.csv','w') as f:

后者是您将数据写入的行(在不断增长的行中,因为data在写入CSV后永远不会被清除。)

您可能正在桌面上查看第一个文件,而另一个文件是在您当前的工作目录中创建的(可以在任何地方,您不会显示您的运行方式)这段代码)。桌面上的那个文件确实是空的。

使用完整路径打开文件一次。写完一行之后的data列表,或者更好的是,只需使用生成器将单元格文本直接发送到writer.writerow()方法:

path = "/Users/alihamed/Desktop/PopulationsOfCountries.csv"
with open(path, 'w') as f:
    writer = csv.writer(f)

    for tables in soup.findAll("table",{"class": "sortable wikitable"}):
        for tr in tables.findAll("tr"):
            writer.writerow(td.string for td in tr.find_all('td'))

无需在文件上调用.close(); with会照顾你。