温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎样读写csv文件

发布时间:2021-08-13 13:41:40 来源:亿速云 阅读:169 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关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('”暂无简介“')
  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']
 # 翻到最后一页
 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) + '页的内容-----------')
csv_file = open('D:/top250_books.csv', 'w', newline='', encoding='utf-8')
w = csv.writer(csv_file)
w.writerow(['书名', '评分', '简介', '链接'])
for b in books:
 w.writerow(b)

结果

python怎样读写csv文件

2.把评分为9.0的书籍保存到book_out.csv文件中

'''
1.爬取豆瓣评分排行前250本书,保存为top250.csv
2.读取top250.csv文件,把评分为9.0以上的书籍保存到另外一个csv文件中
'''
import csv
#打开的时候必须用encoding='utf-8',否则报错
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)
  #把头部信息写进去
  writer.writerow(headers)
  for book in reader:
   #获取评分
   score = book[1]
   #把评分大于9.0的过滤出来
   if score and float(score) >= 9.0:
    writer.writerow(book)

感谢各位的阅读!关于“python怎样读写csv文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI