#!/user/bin/env python# -*- coding:utf-8 -*-# author:berlin# ---------------------------注意----------------------------# (1)文件只有三种模式:r代表只能读;w代表只能写;a代表可以在文末追加文字# (2)在w模式下,打开open文件时,又接着write新的文字。那么结果是:清空原文件的内容,写入新的内容。# 这种情况会造成删库影响。切记!!切记!!切记!!#1、打开文件。r=read、w=write、a=append# sing = open('《yesterday once more》歌词','a') #文件句柄#2、写入# sing.write('真是好听!\n')# sing.write('再听一遍。')# 3、关闭# sing.close()# 实例1:打开文件,只能读# sing = open('《yesterday once more》歌词','r') #文件句柄# print(sing.read())# 实例2:打开文件,只能写(注意:此处写代表重写文件,会造成删库影响。谨慎使用!!!!!切记!!!)# sing = open('《yesterday once more》歌词','w') #文件句柄# sing.write('真是好听!\n')# sing.write('再听一遍。')# 实例3:打开文件,并且在文末追加文字# sing = open('《yesterday once more》歌词','a') #文件句柄# sing.write('\n真是好听!\n')# sing.write('再听一遍。')#实例4:打开文件,既能读也能写(类似于追加)(读写)# sing = open('《yesterday once more》歌词','r+') #文件句柄# sing.readline() # 先打印3行# sing.readline()# sing.readline()# sing.tell()# sing.write('--------------------------新加----------------')# sing.readline() #继续打印#实例4:打开文件,既能写也能读(写读)# sing = open('《yesterday once more》歌词','r+') #文件句柄# sing.write('------新的一句---') # 先创建一个新文件写4行# sing.write('------新的一句---')# sing.write('------新的一句---')# sing.write('------新的一句---')# print(sing.tell())# sing.seek(5)# print(sing.tell())# print(sing.readline())# sing.write('!!!!!!!!!!!!!!!继续写!!!!!!') #继续写入# sing.closed #关闭#实例5:打开文件,追加读写# sing = open('《yesterday once more》歌词','a+') #文件句柄#实例6:打开文件,读取二进制文件(两种情况下使用rb:(1)网络传输只能二进制格式;(2)一些下载文件的读取打开)# sing = open('《yesterday once more》歌词','rb') #文件句柄#实例6:打开文件,写二进制文件# sing = open('《yesterday once more》歌词','wb') #文件句柄#读取前五行# sing = open('《yesterday once more》歌词','r') #文件句柄# for i in range(5):# print(sing.readline())#循环该文件所有行,但跳过第十行不打印# (1)比较low的写法# sing = open('《yesterday once more》歌词','r') #文件句柄# for index,i in enumerate(sing.readlines()):# if index == 9:# print('----------------------------------------我是分割线----------------------------------------')# continue# print(i)#(2)高级写法,效率高的写法# sing = open('《yesterday once more》歌词', 'r') # 文件句柄# count = 0# for i in sing:# if count == 9:# print('--------------------------我是分割线----------------------------------------')# count += 1# continue# print(i)# count += 1#tell和seek的用法# sing = open('《yesterday once more》歌词', 'r') # 文件句柄# print(sing.tell()) #该tell指初始字符所在的位置的index# print(sing.read(50))# print(sing.tell()) #该tell指读取50行字符所在的位置的index# sing.seek(0) #该seek指返回到指定index的位置# print(sing.readline())#查看文件使用的字符编码# sing = open('《yesterday once more》歌词', 'r') # 文件句柄# print(sing.encoding)## sing = open('《yesterday once more》歌词', 'r') # 文件句柄# print(sing.buffer)#方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。# 一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。# sing = open('《yesterday once more》歌词', 'r') # 文件句柄# print(sing.flush())# (1)flush实现进度条作用:# import sys,time# for i in range(20):# sys.stdout.write('#') #stdout指标准输出,stdin指标准输入# sys.stdout.flush()# time.sleep(0.1) #指定时间间隔#truncate指截断# sing = open('《yesterday once more》歌词', 'a') # 文件句柄# sing.truncate(sing.seek(20) ) #先是指定到第20个字符,然后从20开始截断