Python 读写文件(open、pickle)
2017-05-08 00:00
309 查看
Character | Meaning |
---|---|
‘r’ | open for reading (default) |
‘w’ | open for writing, truncating the file first |
‘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 (for backwards compatibility; should not be used in new code) |
模式 | 描述 |
---|---|
rt | 读取文本,默认模式 |
rb | 读取二进制数据 |
wt | 写入文本 |
wb | 写入二进制 |
r+ | 不清空原文件,读写 |
w+ | 清空原文件,并读写 |
a+ | 在文件末尾读写 |
I
love
CSDN
只读模式(默认模式)
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","r") >>>>print(f.read()) I love CSDN >>>>f.close()
写入模式
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","w") >>>>f.write("test") >>>>f.close()
输出的结果是:
test
在使用”w”模式时,python会把原来的文件给覆盖掉,形成新的文件,这里注意如果写入的文件不存在,python会自动新建一个文件。
追加模式
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","a") >>>>f.write("test") >>>>f.close()
输出的结果是:
I
love
CSDNtest
另外我们还可以设定读取和写入的方式:
以二进制方式读取:
>>>>f=open("C:/Users/Administrator/Desktop/abc.txt","rb") >>>>print(f.read()) >>>>f.close() b'I\r\nlove\r\nCSDN'
而以二进制读取的一个妙用就是保存matplotlib的交互式图片页面:
保存交互式图片页面
import matplotlib.pyplot as plt import pickle as pl #调用matplotlib的figure对象 fig = plt.figure() x = [1,2,3,4,5] y = [1,2,3,4,5] plt.plot(x,y) #序列化figure对象,并保存 pl.dump(fig,open('C:/Users/Administrator/Desktop/fig.pickle','wb'))
读取交互式页面:
import matplotlib.pyplot as plt import pickle as pl # 载入序列化文件 fig = pl.load(open('C:/Users/Administrator/Desktop/fig.pickle','rb')) plt.show() # 获得图片信息 print(fig.axes[0].lines[0].get_data())
相关文章推荐
- Python open读写文件实现脚本
- open()文件对象的seek、tell方法详解 分类: python基础学习 open()文件读写 python Module 2013-09-05 09:40 450人阅读 评论(0) 收藏
- python 文件读写时用open还是codecs.open
- python 读写文件函数open()用法
- python-open()-文件读写
- Python open读写文件实现脚本
- python 文件读写时用open还是codecs.open
- python文件读写(open参数,文件缓冲,内存映射,临时文件)
- python 列表 字典 读写文件:pickle模块的基本使用
- Python文件读写 - 文件r+ a+ open读写实际表现[示例]
- python open文件 读写模式说明
- Python文件操作,open读写文件,追加文本内容(转)
- 文件操作注意事项 分类: python 小练习 python基础学习 open()文件读写 2013-12-03 11:05 532人阅读 评论(0) 收藏
- Python 文件操作中的读写模式:open(path, '-模式-',encoding='UTF-8')
- Python open读写文件实现脚本
- 【python】Python open读写文件
- Python open读写文件实现脚本
- Python天天美味(17) - open读写文件
- python 文件读写时用open还是codecs.open
- Python文件操作,open读写文件,追加文本内容