6.文件操作

  1 '''
  2 file = open("test",'r',encoding="utf-8")
  3 
  4     'r'       open for reading (default)
  5     'w'       open for writing, truncating the file first
  6     'x'       create a new file and open it for writing
  7     'a'       open for writing, appending to the end of the file if it exists
  8     'b'       binary mode
  9     't'       text mode (default)
 10     '+'       open a disk file for updating (reading and writing)
 11     'U'       universal newline mode (deprecated)
 12 '''
 13 
 14 #data = file.read()#一次性读到底部
 15 
 16 '''
 17 读取操作演示
 18 '''
 19 
 20 file = open("test","r",encoding="utf-8")
 21 
 22 '''
 23 读取前几行
 24 for l in range(5):
 25     print(file.readline().strip())
 26 
 27 读取指定某行的内容 只适合读小文件 
 28 for index,line in enumerate(file.readlines()):
 29     if index == 9:
 30         print(line)
 31         
 32 自动开启迭代,效率比较高,推荐使用
 33 for line in file:
 34     print(line)
 35 
 36 count = 0
 37 for line in file:
 38     if count == 9:
 39         print(line)
 40     count+=1
 41 '''
 42 
 43 #每次读的字符数
 44 print(file.read(2))
 45 print(file.tell())
 46 
 47 #指定读取几个字符
 48 print(file.read(4))
 49 
 50 #光标移动
 51 print(file.seek(0))
 52 print(file.read(2))
 53 
 54 #打印文件编码
 55 print(file.encoding)
 56 
 57 
 58 file.close()
 59 
 60 '''打印进度条
 61 
 62 import  sys,time
 63 
 64 for i in range(50):
 65     time.sleep(0.1)
 66     sys.stdout.flush()
 67     sys.stdout.write("#")
 68 '''
 69 
 70 
 71 # f  = open("test","a",encoding="utf-8")
 72 # #从头开始截取几个字符,参数为null则是清空文件
 73 # #file.truncate(10)
 74 # f.truncate(3)
 75 
 76 '''
 77 常用到
 78 既可以读又可以写
 79 r+ 读与追加方式写
 80 '''
 81 f = open("test","r+",encoding="utf-8")
 82 print(f.readline())
 83 print(f.write("123r+"))
 84 
 85 '''
 86 很少用到
 87 w+ 写读 ,先创建空文件在写
 88 '''
 89 
 90 f = open("test","w+",encoding="utf-8")
 91 f.write("w+")
 92 
 93 ''' 95 a+ 追加读写
 96 '''
 97 f = open("test","a+",encoding="utf-8")
 98 
 99 
100 '''
101 很少用到
102 rb 读二进制文件
103 '''
104 f = open("test","rb",encoding="utf-8")
105 
106 ###########################with 方法自动关闭资源##############
107 
108 #with open as f1
109 #with可以自动关闭资源
110 with   open("test","r",encoding="utf-8") as f1,\
111     open("test.bak","w",encoding="utf-8") as f2:
112     for line in f1:
113         print(line.strip())

 

posted @ 2017-09-09 14:30  家阳光  阅读(174)  评论(0)    收藏  举报