f = open(“today”,encoding=“utf-8”)#.read()
‘’'print(f)
f = open(“today”,“r”,encoding=“utf-8”)#文件句柄
data = f.read()
data2 = f.read()
print(data)
print("-----------------------",data2)
#写文件
f1= open(“today1”,“w”,encoding=“utf-8”)#文件句柄
f1.write(“43214\n”)#创建一个文件,有文件会覆盖
f1.write(“需要手动换行\n”)
#追加文件
f1= open(“today1”,“a”,encoding=“utf-8”)#文件句柄
f1.write(“尝试尝试\n”)
f1.close()
f1= open(“today1”,“r”,encoding=“utf-8”)
for i in range(2):
print(f1.readline(5))
for line in f.readlines():#循环列表
print(line.strip())
‘’’
for index,line in enumerate(f.readlines()):#读取数据建立列表,并循环列表
if index == 4:
print("我是分割线")
continue
print(line.strip())
#内存中只保存一行数据
count = 0
for line in f:
if count == 4:
print(“我是分割线”)
count +=1
continue
print(line)
print(f.tell())#去光标值
f.seek(0)#光标回到指定位置
print(f.fileno())#返回文件内存编号
print(f.isatty())#判断文件是否为终端设备(如打印机是一个终端设备)
print(f.seekable())#判断文件能不能移动光标
print(f.flush())#强制刷新
f.truncate(20)#从头开始截断到指定字符
#读写
f1= open(“today1”,“r+”,encoding=“utf-8”)
print(f1.readline())
print(f1.readline())
f1.write("----------diao-----")#写在最后一行
print(f1.readline())
#写读
f1= open(“today1”,“w+”,encoding=“utf-8”)
#追加写读
f1= open(“today1”,“a+”,encoding=“utf-8”)
#二进制
f1= open(“today1”,“rb”)#网络传输只能用二进制传输
print(f.readline())
print(f.readline())
print(f.readline())
#文件的修改
#方法一:文件全部读取到内存,修改后再全部写回
#方法二:文件修改后写成新文件
f3 = open(“today”,“r”,encoding=“utf-8”)
f_new = open(“today2”,“w”,encoding=“utf-8”)
for line in f3:
if “remove” in line:
line = line.replace(“remove”,“move”)
f_new.write(line)
f3.close()
f_new.close()
#with使用方法
#官方Python书写规范要求单行不能超过80个字符
with open(“today”,“r”,encoding=“utf-8”) as f5,
open(“today1”,“r”,encoding=“utf-8”) as f6:
for line in f5:
print(line)