Python优化:文件的读写及下载保存
读入写出功能在爬虫和平时处理文件时候非常有用,本文会从以下几个方面总结:
- open和with…open及其之后的操作。
- 图片的下载
一. 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().
Method | Details |
---|---|
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')