python文件的高级应用

文件的高级应用

一、可读,可写

  • r+t : 可读,可写
  • w+t :可写,可读
  • a+t : 可追加,可读
#wt
with open('36w.txt'.'wt',encoding='utf-8') as fw:
    print(fw.readable())#检测是否可读
#输出:
False   # 不能读取
    print(fw.writable())#检测是否可写
#输出:
True   # 可以写
#w+t
with open('36.txt','w+t',encoding='utf-8') as fw:
    print(fw.readable())
 #输出:
True  #可读取
    print(fw.writable())
#输出:
True   #  可以写
#r+t
with open('36.txt','r+t',encoding='utf-8') as fw:
    print(fw.readable())
 #输出:
True  #可读取
    print(fw.writable())
#输出:
True   #  可以写

二、文件内指针的移动

假设我们需要在文件内容中间的某一行增加内容,如果使用基础的r、w、a模式实现是非常困难的,因此我们需要多文件内的指针进行移动。

with open('36.txt','r+t',encoding='utf-8') as fr:
    fr.readline()
    fr.write('大帅逼')#写到文件最后一行

硬盘上没有修改的说法,硬盘上只有覆盖,即新内容覆盖原来的内容。

  1. seek(offset,whence):offset代表文件指针的偏移量,单位是字节

    # seek(offset,whence)
    with open('36.txt','rt',encoding='') as fr:
        print(f"fr.seek(3,0):{fr.seek(3,0)}")#0相当于文件头开始,1相当于当前文件所在的位置,2相当于文件末尾
        #fr.seek(0,2)#切换到文件末尾
  2. tell():每次统计都是从文件开头到当前指针所在的位置。

    #tewll # 计算指针前面有多少字符
    with open('36.txt','rt',encoding='utf-8') as fr:
        fr.seek(4,0)
        print(fr.tell())
  3. read(n):只有在模式下的read(n),n代表的是字符个数,除此之外,其他但凡涉及文件指针的都是字节个数。

    #read
    with open('36.txt','rt',encoding='utf-8') as fr:
        print(fr.read(3))#读出指针后n位
  4. truncate(n):truncate(n)是截断文件,所以文件的打开法师必须是可写,但是不能用w、w+等方式打开,因为那样直接清空文件的内容了,所以truncate(n)要在r+、a、a+等模式下测试效果。它的参照物永远是文件头,并且truncate()如果没有参数的话,就相当于直接清空文件。

with open('36.txt','r+t',encoding='utf-8') as fr:
    fr.truncate(3)

猜你喜欢

转载自www.cnblogs.com/chenziqing/p/11321102.html