#文件操作的基本流程:
#文件的读取 #
# file = open("小重山","r",encoding="utf-8")#操作句柄,打开文件,指定文件操作类型为r,字符集为utf-8
# data = file.read()#读取文件全部内容
# data1 = file.read(5)#读取文件前5个字符的内容
# print(data)#打印文件内容
# print(data1)#打印文件内容
# file.close()#关闭文件
#文件的写入#
# file = open("小重山","w",encoding="utf-8")#操作句柄,打开文件,指定文件操作类型为w,字符集为utf-8
# data = file.write("呵呵呵哒")#把内容写入文件,会先格式化文件,在添加内容,返回添加的字符长度
# print(data)#打印文件内容
# file.close()#关闭文件
#文件的追加#
# file = open("小重山","a",encoding="utf-8")#操作句柄,打开文件,指定文件操作类型为a,字符集为utf-8
# data = file.write("呵呵呵哒")#把内容写入文件,会替换原先的内容,返回的追加的字符长度
# print(data)#打印文件内容
# file.close()#关闭文件
#文件的其他操作#
示例1:
# file = open("小重山","r",encoding="utf-8")
# print(file.readline())#默认读取第一行
# print(file.readline())#接着上面的读取下一行
# print(file.readlines())#打印所有行吗,返回的是一个列表
# data = file.readlines()
# file.close()
# data.insert(6,"i like you")
# for i in data:
# print(i.strip())
示例2:
# file = open("小重山","r",encoding="utf-8")
# file1 = open("小重山2","w",encoding="utf-8")
# num = 0
#
# for i in file:
# if num == 5 :
# i = (" ".join([i.strip(),"ccy
"]))
# file1.write(i)
# num+=1
# file1.close()
# file.close()