文件的高级应用

可读、可写

  • r+t: 可读、可写
  • w+t: 可写、可读
  • a+t: 可追加、可读
# wt
with open('36w.txt', 'wt', encoding='utf-8') as fw:
    print(fw.readable())
    print(fw.writable())
False
True
# w+t
with open('36w.txt', 'w+t', encoding='utf-8') as fw:
    print(fw.readable())
    print(fw.writable())
True
True
# r+t
with open('36w.txt', 'r+t', encoding='utf-8') as fr:
    print(fr.readable())
    print(fr.writable())
True
True

文件内指针移动

假设咱们须要在文件内容中间的某一行增长内容,若是使用基础的r/w/a模式实现是很是困难的,所以咱们须要对文件内的指针进行移动。测试

with open('36r.txt', 'r+t', encoding='utf-8') as fr:
    fr.readline()
    fr.write('nick 真衰呀')  # 写在文件的最后一行

硬盘上历来没有修改一说,硬盘上只有覆盖,即新内容覆盖新内容。指针

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

# seek()
with open('36r.txt', 'rb') as fr:
    print(f"fr.seek(4, 0): {fr.seek(4, 0)}")  # 0至关于文件头开始;1至关于当前文件所在位置;2至关于文件末尾
    # fr.seek(0,2)  # 切换到文件末尾
fr.seek(4, 0): 3

2.tell(): 每次统计都是从文件开头到当前指针所在位置utf-8

# tell()
with open('36r.txt', 'rb') as fr:
    fr.seek(4, 0)
    print(f"fr.tell(): {fr.tell()}")
fr.tell(): 4

3.read(n): 只有在模式下的read(n),n表明的是字符个数,除此以外,其余但凡涉及文件指针的都是字节个数it

# read()
with open('36r.txt', 'rt', encoding='utf-8') as fr:
    print(f"fr.read(3): {fr.read(3)}")
fr.read(3): sdf

4.truncate(n): truncate(n)是截断文件,因此文件的打开方式必须可写,可是不能用w或w+等方式打开,由于那样直接清空文件了,因此truncate()要在r+或a或a+等模式下测试效果。它的参照物永远是文件头。而且truncate()不加参数,至关于清空文件。table

# truncate()
with open('36r.txt', 'ab') as fr:
    fr.truncate(2) # 截断2个字节后的全部字符,若是3个字节一个字符,只能截断2/3个字符,还会遗留1/3个字符,会形成乱码
相关文章
相关标签/搜索