python讀寫csv文件的方法
1.爬取豆瓣top250書籍
import requests
import json
import csv
from bs4 import BeautifulSoup
books = []
def book_name(url):
res = requests.get(url)
html = res.text
soup = BeautifulSoup(html, 'html.parser')
items = soup.find(class_="grid-16-8 clearfix").find(class_="indent").find_all('table')
for i in items:
book = []
title = i.find(class_="pl2").find('a')
book.append('《' + title.text.replace(' ', '').replace('\n', '') + '》')
star = i.find(class_="star clearfix").find(class_="rating_nums")
book.append(star.text + '分')
try:
brief = i.find(class_="quote").find(class_="inq")
except AttributeError:
book.append('”暫無(wú)簡(jiǎn)介“')
else:
book.append(brief.text)
link = i.find(class_="pl2").find('a')['href']
book.append(link)
global books
books.append(book)
print(book)
try:
next = soup.find(class_="paginator").find(class_="next").find('a')['href']
# 翻到最后一頁(yè)
except TypeError:
return 0
else:
return next
next = 'https://book.douban.com/top250?start=0&filter='
count = 0
while next != 0:
count += 1
next = book_name(next)
print('-----------以上是第' + str(count) + '頁(yè)的內(nèi)容-----------')
csv_file = open('D:/top250_books.csv', 'w', newline='', encoding='utf-8')
w = csv.writer(csv_file)
w.writerow(['書名', '評(píng)分', '簡(jiǎn)介', '鏈接'])
for b in books:
w.writerow(b)
結(jié)果

2.把評(píng)分為9.0的書籍保存到book_out.csv文件中
'''
1.爬取豆瓣評(píng)分排行前250本書,保存為top250.csv
2.讀取top250.csv文件,把評(píng)分為9.0以上的書籍保存到另外一個(gè)csv文件中
'''
import csv
#打開(kāi)的時(shí)候必須用encoding='utf-8',否則報(bào)錯(cuò)
with open('top250.csv', encoding='utf-8') as rf:
reader = csv.reader(rf)
#讀取頭部
headers = next(reader)
with open('books_out.csv', 'w', encoding='utf-8') as wf:
writer = csv.writer(wf)
#把頭部信息寫進(jìn)去
writer.writerow(headers)
for book in reader:
#獲取評(píng)分
score = book[1]
#把評(píng)分大于9.0的過(guò)濾出來(lái)
if score and float(score) >= 9.0:
writer.writerow(book)
總結(jié)
以上所述是小編給大家介紹的python讀寫csv文件的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
相關(guān)文章
python字典setdefault方法和get方法使用實(shí)例
這篇文章主要介紹了python字典setdefault方法和get方法使用實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
Django將默認(rèn)的SQLite更換為MySQL的實(shí)現(xiàn)
今天小編就為大家分享一篇Django將默認(rèn)的SQLite更換為MySQL的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
利用Python實(shí)現(xiàn)繪制3D愛(ài)心的代碼分享
最近你是否也被李峋的愛(ài)心跳動(dòng)代碼所感動(dòng),心動(dòng)不如行動(dòng),相同的代碼很多,我們今天換一個(gè)玩法!構(gòu)建一個(gè)三維的跳動(dòng)愛(ài)心!嗯!這篇博客本著開(kāi)源的思想!不是說(shuō)誰(shuí)對(duì)浪漫過(guò)敏的2022-11-11
Python實(shí)現(xiàn)自動(dòng)識(shí)別數(shù)字驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了如何使用Python來(lái)自動(dòng)識(shí)別數(shù)字驗(yàn)證碼,以便在需要時(shí)自動(dòng)填寫或驗(yàn)證驗(yàn)證碼,有需要的小伙伴可以參考一下2024-04-04
OpenCV-Python實(shí)現(xiàn)圖像平滑處理操作
圖像平滑處理的噪聲取值主要有6種方法,本文主要介紹了這6種方法的具體使用并配置實(shí)例方法,具有一定的參考價(jià)值,感興趣的可以了解一下2021-06-06

