文件操作:
1.打开文件:
只读:
open('nn','r',encoding = 'utf-8')
清空内容写文件:
open('nn',w,encoding = 'utf-8')
文件存在报错,不存在,创建并写文件
open('nn','x',encoding = 'utf-8')
追加:
open('nn','a',encoding = 'utf-8')
若打开方式带‘b’,则以二进制形式字节读.(适用于跨平台)
open('nn','rb')
以b形式打开文件,将字符串“你好”以“utf-8”编码方式追加到文件“nn”,并将字符串转换为字节形式,以二进制写入nn
eg:
f = open('nn','ab')
f.write(bytes("你好",encoding = 'utf-8'))
f.close()
读写方式:r+,a+,w+,x+:
eg:
f = open('nn','r+',encoding = 'utf-8')
data = f.read()
print(data)
f.write("abcdefg")
f.close()
带+为可读写:
a+无论怎样调节指针位置,写时永远在最后位置 w+要先清空 常用r+
seek()指针移动,只按字节移动
tell()获取当前指针位置
eg:
f = open('nn','r+',encoding = 'utf-8') 如果打开方式无b,则按字符读,如果有b,则按字节读
data = f.read(1) 如果打开方式是r+b,则读取1个字节;如果无b,则读取1个字符
print(data)
print(f.tell()) 获取当前指针位置,为字节位置
f.seek(1) 移动一个字节位置
f.write("abcdefg") 从当前指针位置开始向后覆盖写入
f.close()
2.文件操作:
read()无参数,读全部;有参有b按字节,无b按字符 tell()获取当前指针位置(按字节) seek(位置)指针跳转到指定位置(按字节) write()写数据,有b字节,无b字符 fileno()文件描述符 flush()将缓冲区的数据强刷到硬盘 readable()判断是否可读 readline()仅读取一行 truncate()截断数据,保留指针位置前的数据,指针位置后的数据清,一般配合seek()使用
for循环文件句柄,循环每一行读取数据(常用): for line in f: print(line)
3.关闭文件:
close()关闭文件;
操作完自动关闭
with open('xxxx') as f:
pass
同时打开两个文件
with open("abc") as f1,open("def") as f2
pass
eg:
with open("abc","r",encoding = "utf-8") as f1,with open("def","w",encoding = "utf-8") as f2:
for line in f1:
newline = line.replace("jiang","chen")
f2.write(newline)