Python入门基础学习六

文件处理

文件系统基本操作

f=open('陈米',encoding='utf-8')
date=f.read()
print(date)
f.close()

文件处理读取操作

f=open('陈米','r',encoding='utf-8')
# date=f.read()
print(f.readable())
print('第一行', f.readline(),end=" ")
print('第二行', f.readline(),end='')
print('第三行', f.readline())
print('第四行', f.readline())
print('第五行', f.readline())
date=f.readline()
print(date)
f.close()

文件处理写操作

f=open('陈米','w',encoding='utf-8')#若文件存在,直接清空
f.write('1111\n')
f.write('2222\n')
f.write('3333\n')
# f.writable()
f.writelines(['444\n','5555\n'])#文件内容只能是字符串,只能写字符串
f.close()

文件处理只追加模式

f=open('陈米','a',encoding='utf-8')
f.write('写到文件最后')
f.close()

文件处理其他方式

#可读可写
f=open('陈米','r+',encoding='utf-8')
# date=f.read()
# print(date)
f.write('sb')#文件只从光标位置开始写,覆盖


# 修改
src_f=open('陈米','r',encoding='utf-8')
date=src_f.readlines()#呈现的是列表
src_f.close()
dst_f=open('陈米','w',encoding='utf-8')
dst_f.write(date[0])#只能写字符串
dst_f.close()

#with操作省去close操作
with open('a.txt','w') as f:#省去close操作
    f.write("111\n222\n")

with open('陈米','r',encoding='utf-8') as src_f ,\
    open('陈米1','w',encoding='utf-8') as dst_f:
    data=src_f.read()
    dst_f.write(data)

 文件处理b模式

f= open("陈米",'rb')  #b的方式不能指定编码
#‘字符串’------encode-----》bytes 编码
#'bytes-----decode---->'字符串‘ 解码
data=f.read()
print(data)
print(data.decode('utf-8'))


f=open('test.py','wb')
f.write(bytes('111\n',encoding='utf-8'))
f.write('张赞'.encode('utf-8'))\


f=open('test.py','ab')#"ab'指的是最后一个位置写入
f.write('杨戬'.encode('utf-8'))

文件操作的其他方法

f=open("a1.txt",'w+',encoding='utf-8',newline='')#"newline'读取真正换行符号
print(f.closed)#状态是否打开

print(f.encoding)#取文件打开的编码,与源文件以什么方式存放硬盘无关系

print(f.flush())#刷新

print(f.tell())#当前光标的位置
# # f.readline()
# # print(f.tell())#当前光标的位置
print(f.readlines())
print(f.tell())#当前光标的位置
f.readline()
print(f.tell())#当前光标的位置

f.seek(3)#控制光标移动,以字节为单位
print(f.tell())
print(f.readlines())

data=f.read(2)#以字符为单位,读位置
print(data)

f.truncate(10)#文件截断

#seek默认开始位置,为0
f=open('a1.txt','r',encoding='utf-8')
print(f.tell())
f.seek(10,0)
print(f.tell())
f.seek(3,0)
print(f.tell())
#seek相对位置为1,2是从文件末尾倒过去(前面加负号)。但必须是rb模式
f=open('a1.txt','rb')
print(f.tell())
f.seek(10,1)
print(f.tell())
f.seek(3,1)
print(f.tell())
f=open('a1.txt','rb')
f.seek(-5,2)
print(f.tell())
print(f.read())

#如何用seek读取最后一行
f=open('a1.txt','rb')
for i in f:#循环文件用此方法
    offs=-10
    while True:
        f.seek(offs,2)
        data=f.readlines()
        if len(data) > 1 :
            print('文件最后一行是%s'%(data[-1].decode('utf-8')))
            break
        offs*=2

猜你喜欢

转载自www.cnblogs.com/zhangzanyao/p/12776308.html
今日推荐