- 首先新建一个文件
- 文件操作步骤
- 打开
- 操作
- 关闭
- 文件读操作
- 读的同时不可写
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') data = f.read() print(data) f.close()
输出:
- 只能读1次,不可多次读操作
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') data = f.read() data2 = f.read() print(data) print('----------data2-------------',data2) f.close()
- 不同姿势的输出
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') data = f.read() data2 = f.read() print(data) print('----------data2-------------',data2) print('------------data2--%s------------'%data2) print('------------data2------------------%s'%data2) f.close()
- 写的时候不可读操作, 删除原有的内容重写
#Author:Kevin_hou f = open('机器铃 砍菜刀','w',encoding='utf-8') f.write('I love Beijing TianAn door') f.close()
- 读前3行
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') for i in range (3): print(f.readline()) f.close()
- 打印一份文件
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') print(f.readlines()) f.close()
- 打印一份文件
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') for line in f.readlines(): print(line.strip()) f.close()
- 在第三行插入,f.readlines只适合小文件插入
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') for index,line in enumerate(f.readlines()): if index ==3 : print('*************分割线*************') continue print(line.strip()) f.close()
- 一行行读
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') count = 0 for line in f : if count == 4: print('#############################') count += 1 continue print(line.strip()) count += 1 f.close()
- 输出当前光标位置
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') print(f.tell()) f.close()
输出当前光标位置,按照字符计数
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') print(f.tell()) print(f.readline()) print(f.tell()) print(f.readline()) print(f.tell()) f.close()
- 返回光标值,f.seek()
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') print(f.tell()) print(f.readline()) print(f.tell()) print(f.readline()) print(f.tell()) f.seek(0)#光标回到0 print(f.readline()) print(f.tell()) f.seek(2)#光标回到2 print(f.tell()) f.close()
- 刷新使修改生效
#Author:Kevin_hou f = open('机器铃 砍菜刀','r',encoding='utf-8') print(f.flush()) #刷新使修改生效 f.close()
- 读写操作‘r+’
#Author:Kevin_hou f = open('机器铃 砍菜刀','r+',encoding='utf-8') #读写操作 print(f.readline()) print(f.readline()) print(f.readline()) f.close()
-
#读写操作,先创建新文件再往里写
#Author:Kevin_hou f = open('机器铃 砍菜刀','w+',encoding='utf-8') #读写操作,先创建新文件再往里写 f.write(' -----------------------NBA--------------') f.close()
- 打印二进制
#Author:Kevin_hou #读2进制模式 f =open("yesterday02",'rb') print(f.readline()) print(f.readline()) print(f.readline()) f.close()
- 写二进制值
#Author:Kevin_hou #读2进制模式 f =open("机器铃 砍菜刀",'wb') f.write('hello binary '.encode()) print() f.close()