python3.x - 【python3】中str转成bytes类型后用csv.writerow()写入csv文件仍然出错
PHPz
PHPz 2017-04-18 09:34:58
0
3
739

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

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

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

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

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()语句了
PHPz
PHPz

学习是最好的投资!

모든 응답(3)
大家讲道理

간단히 읽어보니 궁금한 점이 많네요~

#csv_file = open("rent.csv","wb") # 이 문장은 삭제되고 반복됩니다

으아악

약간 업데이트

csv는 텍스트 형식 파일이며 바이너리 쓰기를 지원하지 않으므로 바이너리 모드로 파일을 열지 말고 데이터를 바이트로 변환할 필요도 없습니다.

추가 업데이트

根本原因是楼主看错文档,导致了理解有误~

迷茫

열린 매개변수 'wb'를 'w'로 변경

Ty80

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='' 매개변수가 사용됩니다

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿