Python·读写文件

阅读 70

2021-09-30

f=open('文件路径','打开模式')

模式分为:

我今天想爬取一个网页的源码,然偶直接将源码保存在txt里,遇到 TypeError: write() argument must be str, not bytes


#coding:utf-8

import urllib

import urllib.request

def get_html(url):

    request=urllib.request.Request(url)

    response=urllib.request.urlopen(request)

    data=response.read()

return data


url='https://movie.douban.com/top250?start=0&filter='

print(get_html(url).decode('utf-8'))

with open('douban.txt','a') as ft:

    ft.write(get_html(url))

在网上搜索,可能是Python内部默认为二进制存储,所以把模式改为二进制的就没有问题了,比如‘wb+’

精彩评论(0)

0 0 举报