python文档(传送门)关于CSV的一个用法示例:
文件打开的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])
错误提示
可以看到这里输出的house_title, house_location, house_money, house_url类型都是bytes
然而下面还是报了类型错误
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()语句了
ざっと読んだ後、たくさんの疑問があります~
リーリー#csv_file = open("rent.csv","wb")
# この文は削除され、繰り返されます少し更新します
csv はテキスト形式のファイルであり、バイナリ書き込みをサポートしていないため、ファイルをバイナリ モードで開かないでください。データをバイトに変換する必要はありません。
その他の最新情報
根本原因是楼主看错文档,导致了理解有误~
オープンパラメータ「wb」を「w」に変更します
python2.x を「wb」モードで記述する必要がある本当の理由
python2.x で CSV を書き込む場合、CSV ファイルの作成に 'b' パラメーターを追加する必要があります。つまり、 csv.writer(open('test.csv','wb')) です。それ以外の場合はインターレースされます。線が発生します。インターネット上で見つかった説明は次のとおりです。Python が通常にファイルを書き込むとき、デフォルトで各行の末尾に 'n' が追加されます (これは 0x0D)。writerow コマンドの末尾にはさらに 0x0D0A が追加されるため、Windows システムの場合は、 'b' パラメータを使用してバイナリでファイルを書き込む場合、システムのデフォルトでは 0x0D
は追加されません。python3.x では、この目的を達成するために newline='' パラメータが使用されます