参考链接,(1)菜鸟教程 (2)廖雪峰python入门 (3)中文手册 (4)英文文档
file 相关函数:链接
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# #9.r+,读写(可读,可写)
a = open("test.txt","r+",encoding="utf-8")
print(a.tell()) #打开文件后观看指针位置在第几位,默认在起始位置
date = a.read() #第一次读取,指针读取到最后了,(可以加读取的索引位置,3表示只看前三位)
print(date)
a.write("太帅了~~~~~~~~~~~~~~~~~~~啊~~~~~~~~~~~~~~~~~~~~~") #写的时候会把指针调到最后去写
print(a.tell())
a.seek(0) #把指针放在第一位进行第二次读取
date = a.read() #第二次读取
print(date)
a.close()
# ######### with #########
#为了避免打开文件后忘记关闭,可以通过管理上下文。with open('log','r') as f:
# 当with代码块执行完毕时,内部会自动关闭并释放文件资源
with open('log1') as obj1, open('log2') as obj2:
pass
#同时打开两个文件,把a复制到b中,读一行写一行,直到写完
with open("5.log","r",encoding="utf-8") as a,open("6.log","w",encoding="utf-8") as b:
for line in a:
b.write(line)