author = "jolting"
date = "2018-03-20"
读写文件是最常见的IO操作,python内置了读写文件的函数
1。打开文件 即以读的形式打开文件,提供的函数为open,那么操作方式有几种方式,具体见代码

注意: 文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的,如果每次使用判断try,finally比较麻烦,所以python提供了可以帮助自动关闭文件的with方法,通过with方法打开文件,文件使用完毕之后,系统会自动将文件关闭。用法如上图所展示
2.读取文件
读取文件由三种方式
read() 当文件过大时不建议采用 read(size)
readline()
readlines() 当文件过大时不建议采用
3.文件写入
1.只写
with open("3.txt", 'w') as f:
#以只写的方式打开,3.txt不存在则在当前目录下新建
f.write("just write")
f.read()

注意哦,上面我的代码,只写方式写入,读取时是不允许的 ,具体可以看报错
2.追加写 第一次写入,第二次追加写

>>> with open("5.txt", 'w') as f:
... f.write("3123131jixuxie231231")

>>> with open("5.txt", 'a') as f:
... f.write("大师的海鸥")

先写到这里喽,相互进步喽,编码菜鸟的知识笔记
网友评论