Python怎么进行读写文件
本篇内容主要讲解“Python怎么进行读写文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python怎么进行读写文件”吧!

我们一直强调成都做网站、网站建设对于企业的重要性,如果您也觉得重要,那么就需要我们慎重对待,选择一个安全靠谱的网站建设公司,企业网站我们建议是要么不做,要么就做好,让网站能真正成为企业发展过程中的有力推手。专业网络公司不一定是大公司,成都创新互联作为专业的网络公司选择我们就是放心。
| 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+ | 在文件末尾读写 |
首先在左面新建一个”abc.txt”的文件,文件的内容入如下:
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 pltimport 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 pltimport 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怎么进行读写文件”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
本文标题:Python怎么进行读写文件
链接URL:http://www.jxjierui.cn/article/jghoog.html


咨询
建站咨询
