Python随心记--文件操作处理 open()

文件操作处理  open()
r--只读 w---只写 a---追加 x---只写
f = open('xxx','r',encoding='utf-8')   #默认编码gbk、只读
data = f.read()   #读取文件
print(data)
print(f.readable(),end = '')   #可读返回True  end = '' d代表不换行
print(f.readline())   #读取一行
print(f.readlines())   #读取多行
f.close()   #关闭文件
f = open('xxx','w',encoding='utf-8')   #如果文件存在会清空文件内容,不存在就新建文件
f.write('woyongchun')   #不换行
f.write('woyongchun
在一起
')   #会换行
f.writelines(['555
','5666
'])   #写的参数必须是字符串
f.close()   #关闭文件
追加
f = open('xxx','a',encoding='utf-8')   #如果文件存在会清空文件内容,不存在就新建文件,追加到文件的追后
f.write('wodepanpangchun')
f.close()   #关闭文件
r+
f = open('xxx','r+',encoding='utf-8')   #如果文件存在会清空文件内容,不存在就新建文件,追加到文件的追后
data = f.read()
print(data)
f.write('12212')   #如果没有read(),直接写会覆盖
f.close()   #关闭文件
修改文件内容
f = open('xxx','r',encoding='utf-8')   #读出来的内容为一个列表类型,可for循环
data = f.readlines()   #存起来
f.close()   #关闭文件
dst_f = open('xxx','w',encoding='utf-8')   #存到新的文件
dst_f.readlines(data[0])
dst_f.close()
不需要close()写法
with open('a.txt','w',encoding='gbk') as f:   #不需要关闭文件系统自动关闭文件
    f.write('1111
')
with open('a.txt','r') as f,open('a.txt','w',encoding='gbk') as dst_f:   #换行方式:回车
with open('a.txt','r') as src_f,
        open('new.txt','w',encoding='gbk') as dst_f:
    data = src_f.read()
    dst_f.write(data)
b的方式读取
f = open('test.py','rb')   #以字节的方式不能加编码格式
data = f.read()   #读取以字符为单位
print(data.decode('utf-8'))   #转码
b的方式写入
f = open('a.txt','wb')   #以字节的方式不能加编码格式
data = f.write(bytes('11w1
',encoding='utf-8'))   #需要bytes(x,encoding='utf-8')
datas = f.write('11w1www
'.encode('utf-8'))
b的方式追加
f = open('a.txt','ab')   #以字节的方式不能加编码格式
data = f.write(bytes('11w1
',encoding='utf-8'))   #需要bytes(x,encoding='utf-8')
datas = f.write('11w1www
'.encode('utf-8'))
关于编码问题
  
f = open('a.txt','r+',encoding = 'utf-8',newline='')
print(f.encoding)   #获取编码格式
f.flush()   #刷新文件就会写入文件
print(f.tell())   #光标目前所在位置 光标移动以字节为单位
f.seek(3,0)   #控制光标的移动
f.truncate(10)   #以字符微单截取
循环文件,一行一行的循环
f = open('x.txt','rb')
for i in f:   
    print(i)
seek读取文件最后一行(原理:倒着读,不断增加偏移量)
f = open('a.txt','rb')
for i in f:
    offs = -10
    while True:
        f.seek(offs,2)   #倒着读
        data = f.readlines()
        if len(data) > 1:
            print(data[-1].decode('utf-8'))
            break
        offs *= 2
原文地址:https://www.cnblogs.com/Essaycode/p/10105260.html