python中writerow的作用_【python3】中str转成bytes类型后用csv.writerow()写入csv文件仍然出错...

根本原因是Python版本问题python2.x中要求用‘wb’,python3.x中要求用'w'

首先声明:CSV文件是可以用二进制模式写入的

python文档(传送门)关于CSV的一个用法示例:

d2f85fbb073ec2c36acd469159d87a78.png

文件打开的mode是“wb”

with open('rent.csv','wb') as csv_file:

且与Pythone3里面字符串和二进制数据是两种类型,所以要将str类型转换成bytes类型

出错部分代码

#把str类型的housetitle、house_location、house_money编码成bytes类型

house_title = house_title.encode("utf8")

house_location = house_location.encode("utf8")

house_money = house_money.encode("utf8")

house_url = house_url.encode("utf8")

#查看house_title等的类型

print(type(house_title),type(house_location),type(house_money),type(house_url))

# 向csv文件写入数据

with open('rent.csv','wb') as csv_file:

csv_writer = csv.writer(csv_file,delimiter=',')

csv_writer.writerow([house_title, house_location, house_money, house_url])

错误提示

1614f769b40eb2b8751a5fef76086050.png

可以看到这里输出的house_title, house_location, house_money, house_url类型都是bytes

82640440554d47d6fc9dcf5b0ef39cd9.png

然而下面还是报了类型错误

cc64c2d3fe815ae426ea0953d7e5983a.png

Please Tell Me Why?

主程序全部代码

from bs4 import BeautifulSoup

from urllib.parse import urljoin

import requests

import csv

url = "http://nj.58.com/pinpaigongyu/pn/{page}/?minprice=1000_1500"

page = 1

print("fetch: ", url.format(page=page))

# 抓取目标页面

response = requests.get(url.format(page=page))

# 创建一个BeautifulSoup对象

html = BeautifulSoup(response.text, "lxml")

# 获取class=list下的所有li元素

house_list = html.select(".list > li")

for house in house_list:

house_title = house.select("h2")[0].string

house_url = urljoin(url, house.select("a")[0]["href"])

house_info_list = house_title.split()

house_location = house_info_list[1]

house_money = house.select(".money")[0].select("b")[0].string

#把str类型的housetitle、house_location、house_money编码成bytes类型

house_title = house_title.encode("utf8")

house_location = house_location.encode("utf8")

house_money = house_money.encode("utf8")

house_url = house_url.encode("utf8")

#查看house_title等的类型

print(type(house_title),type(house_location),type(house_money),type(house_url))

# 向csv文件写入数据

with open('rent.csv','wb') as csv_file:

csv_writer = csv.writer(csv_file,delimiter=',')

csv_writer.writerow([house_title, house_location, house_money, house_url])

#用with的写法就不用写关闭文件的csv_file.close()语句了

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值