小尹学python

导航

Python:写入和光标的相关功能

#  write 写
file_01 = open('222.txt',mode='a',encoding='utf-8')
file_01.write('\n四小天王')  # 如不加\n会直接写在已有内容最后,如加\n则会换行写
file_01.flush()  # 内容是写到缓冲区,加flush,则会把内容直接写入硬盘
file_01.close()

#  移动光标位置
file_01 = open('222.txt',mode='r+',encoding='utf-8')
file_01.seek(6)
file_01.write('天下无敌')  # 写入会根据当前光标位置,自动覆盖后面的字符
file_01.read(0)
pla = file_01.tell()  # 获取当前光标位置
print(pla)  # 获取当前光标位置,字节位置,如果中文字符,则一个字符占3个字节,输出为6
file_01.close()
#  问题:有乱码
#  如果是a模式,无法调整光标,永远将内容写入尾部

posted on 2021-10-04 23:41  小尹学python  阅读(184)  评论(0编辑  收藏  举报