python基础06--文件操作

1.1 文件操作

1、只读(r,rb)     rbbytes方式读文件

   只写(w,wb)

   追加(a,ab)

r+ 读写  

w+ 写读

a+  追加写读

以什么编码方式储存的文件,就用什么编码方式打开

    默认使用r(只读)

b,则打开是不需要指定编码方式

 

2、相对路径(从当前目录开始找) ../          推荐使用

   绝对路径

只读r

1 f = open(“d:/a.txt”,mode=’r’,encoding=’utf-8’)  
2 content = f.read()
3 print(content)
4 f.close()

只写w   清空后再写入 ,没有文件就创建

1 f = open(“d:/a.txt”,mode=’r’,encoding=’utf-8’)  
2 f.write(“wemon”)
3 f.flush() 
4 f.close()

 

追加a    在原来基础上追加内容 ,没有文件就创建

1 f = open(“d:/a.txt”,mode=’a’,encoding=’utf-8’)  
2 f.write(“wemon”)
3 f.flush()     
4 f.close()

 

rb,wb,ab   处理的是非文本

只读rb

1 f = open(“d:/a.txt”,mode=’rb’,encoding=’utf-8’)  
2 content = f.read()
3 print(content.decode(“utf-8”))   #需要编码
4 f.close()

只读wb

1 f = open(“d:/a.txt”,mode=’rb’,encoding=’utf-8’)  
2 f.write(“你好啊”.encode(“utf-8”))       需要编码在写入
3 print(content.decode(“utf-8”))  
4 f.close()

f.read()读是读的光标后面的内容

读写r+    

默认光标在文件开头,先读后写光标在最后  先写光标在最前面,覆盖写

1 f = open(“d:/a.txt”,mode=’r+’,encoding=’utf-8’)  
2 f.read()
3 f.write(“你好啊”)
4 f.flush()
5 f.close()

写读w+     不好用    

w操作,会清空原来的内容

1 f = open(“d:/a.txt”,mode=’r+’,encoding=’utf-8’)  
2 f.write(“你好啊”)
3 f.seek(0)         移动光标到文件首
4 s = f.read()
5 print(s)
6 f.close()

3、相关操作

神坑r+   如果先读取,在写,写入的是末尾

    在没有任何操作之前去进行写,在开头写

1 f = open(“d:/a.txt”,mode=’r+’,encoding=’utf-8’)  
2 f.read(3)                  #从光标处读三个字符
3 f.write(“你好啊”)          # 写入到末尾
4 f.flush()
5 f.close()

 

seek(n)    从开头光标移动到n位置,移动的单位是byte,所以如果是utf-8,中文需要是3的倍数,英文是1byte

seek(0)    移动到开头

seek(0,2)   移动到结尾,seek第二个参数表示从哪个位置进行偏移,默认是0表示从开头,1表示当前位置,2表示结尾

1 f = open(“d:/a.txt”,mode=’r+’,encoding=’utf-8’)  
2 f.seek(6)                  #移动6个字节,2个字
3 f.read(3)                  #从光标处读三个字符
4 f.seek(0)                 #光标回到开头
5 f.read(3)                 #从开头读三个
6 f.flush()
7 f.close()

4、tell() 当前光标的位置

 

5、文件修改   with as 不用关闭文件

import os
with  open(“d:/a.txt”,mode=’r’,encoding=’utf-8’) as f1 ,
     open(“d:/a.txt”,mode=’w’,encoding=’utf-8’) as f2:
#s = f1.read()         #全部读取完后修改
#ss=s.replace(“肉”,”菜”)
#f2.write(ss)

for line in f:           #一行一行修改
s = line.replace(‘肉’,’菜’)
f2.write(s)
os.remove(“吃的”)
os.rename(‘吃的_副本’)

 

  一行一行读  f.readline()

1 f= open(“file/test.txt”,mode=’r’,encoding=’utf-8’)
2 for line in f:       
3 print(line)
4 f.close()

原文地址:https://www.cnblogs.com/fbug/p/11792813.html