Python优化:文件的读写及下载保存

本文介绍了Python中的文件读写,包括open函数的使用、with语句的优势,以及read(), readline(), readlines()等方法。同时,详细讲解了图片下载的三种方法,涵盖urllib和requests库的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python优化:文件的读写及下载保存

读入写出功能在爬虫和平时处理文件时候非常有用,本文会从以下几个方面总结:

  1. open和with…open及其之后的操作。
  2. 图片的下载

一. open相关的读入写出

1.1 open函数解释

open函数是python的内置函数,函数如下:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

其中最常用的是前两个参数。

file :顾名思义,这是指打开文件的位置

mode:这个是打开方式,默认’rt’ (open for reading text)。以下列举几个常用的mode:

‘r’ open for reading (default)

‘w’ open for writing, truncating the file first

‘x’ create a new file and open it for writing

‘a’ open for writing, appending to the end of the file if it exists

‘b’ binary mode

‘t’ text mode (default)

‘+’ open a disk file for updating (reading and writing)

‘U’ universal newline mode (deprecated)

####1.2 open和with…open区别

#---open的操作方法----
#open需要配合结尾的close()关闭文件
f = open(file,"w")
f.write("Hello,world!")
f.close()

#---with...open的操作方法---
#不需要close(),需要操作都在with...open后面的缩进内,缩进内容执行完文件自动关闭。
with open(file,"w") as f:
  f.write("Hello,world")
1.3 如何读入文件

读入主要用用到函数:read(),readline(),readlines().

MethodDetails
read()读取整个文件,将文件内容放到一个字符串变量中。
readline()每次读取一行,返回的是一个字符串对象。
readlines()一次性读取整个文件,自动将文件内容分析成一个行的列表。
1.4 如何写入文件

写入文件是用write方法,可以参考上1.1.2案例。

f.write(“写入内容”)

二. 图片的下载保存

#爬虫中常用的图片保存,其他文件类型也可以使用此方法。
#方法一
import urllib
url = "https://www.baidu.com/img/baidu_jgylogo3.gif"
data = urllib.urlopen(url).read()
f = file('save_path',"wb")
f.write(data)
f.close()
#方法二
import urllib
url = "https://www.baidu.com/img/baidu_jgylogo3.gif"
urllib.urlretrieve(url,'save_path')
#方法三
import requests
from cStringIO import StringIO
from PIL import Image
url = "https://www.baidu.com/img/baidu_jgylogo3.gif"
response = requests.get(url)
img = Image.open(StringIO(response.content))
img.save('save_path')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值