1. 程式人生 > 其它 >Python-檔案讀寫

Python-檔案讀寫

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 # Author:woshinidaye
  4 
  5 #讀檔案
  6 '''
  7 read() 每次讀取整個檔案,它通常用於將檔案內容放到一個字串變數中。如果檔案大於可用記憶體,為了保險起見,可以反覆呼叫read(size)方法,每次最多讀取size個位元組的內容。
  8 readlines() 之間的差異是後者一次讀取整個檔案,象 .read() 一樣。.readlines() 自動將檔案內容分析成一個行的列表,該列表可以由 Python 的 for ... in ... 結構進行處理。
9 readline() 每次只讀取一行,通常比readlines() 慢得多。僅當沒有足夠記憶體可以一次讀取整個檔案時,才應該使用 readline()。 10 file = open('user_pwd.txt','r') #r文字檔案。rb,表示二進位制檔案 11 print(file.read())#讀取整個檔案 12 print(file.read(2)) 13 print(file.readline()) 14 stu1 123 15 print(file.readline(1)) 16 print(file.readline(10)) 17 readline是一行一行讀取
18 print(file.readlines())#自動將檔案給到列表裡面,但是三種方式都有換行符,艹了 19 20 為了保障檔案呼叫以後被正確關閉,需要通過try....finally來完成 21 ''' 22 23 ''' 24 try: #try/finally 25 file = open('user_pwd.txt','r') 26 print(file.read()) 27 finally: 28 if file: 29 file.close() 30 ''' 31 32 ''' 33
try....finally比較麻煩,可以使用with命令完成 34 ''' 35 36 ''' 37 with open('user_pwd.txt','r') as file: 38 print(file.read()) 39 ''' 40 41 #readline:讀取一行,以文字形式,2就代表前兩列 42 ''' 43 with open('user_pwd.txt','r') as file: 44 print(file.readline()) 45 with open('user_pwd.txt','r',encoding='utf-8') as file: 46 print(file.readline(2)) 47 ''' 48 49 #readlines:以列表的形式讀取,2就表示 0 1 兩個元素 50 51 ''' 52 with open('user_pwd.txt','r') as file: 53 print(file.readlines()) 54 with open('user_pwd.txt','r') as file: 55 print(file.readlines(2)) 56 ''' 57 #['stu1 123\n', 'stu2 123\n', 'stu3 123\n', 'stu4 123'] 58 #['stu1 123\n'] 59 #三種讀取方式都有換行符,另外兩種看不到是因為print認為是換行,所以不是\n 60 61 ''' 62 with open('user_pwd.txt','r') as file: 63 list = file.readlines() 64 #去除換行符 65 for i in range(0,len(list)): 66 list[i] = list[i].strip('\n') 67 print(list) 68 ''' 69 70 #寫檔案 w:寫文字檔案,wb,寫二進位制檔案 71 ''' 72 with open('user_pwd.txt','w') as file: 73 file.write('stu05 123') 74 with open('user_pwd.txt','r') as read_file: 75 print(read_file.read()) 76 ''' 77 #直接用w,若沒有檔案,建立一個新檔案,然後寫新文字進去;若檔案存在,清空以後,寫入文字檔案; 78 #直接可以用a,不過需要注意格式! 79 ''' 80 with open('user_pwd.txt','a') as file: 81 file.write('stu06 123') 82 with open('user_pwd.txt','r') as read_file: 83 print(read_file.read()) 84 ''' 85 86 ''' 87 with open('user_pwd.txt','w') as file : 88 file.writelines(['1','2','3']) 89 with open('user_pwd.txt','r') as read_file: 90 print(read_file.read()) 91 #結果是123 92 93 with open('user_pwd.txt','w') as file : 94 file.writelines('123') 95 with open('user_pwd.txt','r') as read_file: 96 print(read_file.read()) 97 #結果還是123 #readlines接收列表 98 99 with open('user_pwd.txt','w') as file : 100 file.writelines(['stu1 123\n','stu2 123\n','stu3 123\n']) 101 with open('user_pwd.txt','r') as read_file: 102 print(read_file.readlines()) 103 #需要手動指定換行符 104 ''' 105 106 ''' 107 username = input('please enter your username:') 108 password = input('please enter your password:') 109 with open('user_pwd.txt','w') as file : 110 file.writelines([username,password]) 111 with open('user_pwd.txt','r') as read_file: 112 print(read_file.readlines()) 113 #這樣寫格式還是不對 114 ''' 115 116 ''' 117 username_list = [] 118 username = input('please enter your username:') 119 username_list.append(username) 120 #print(username_list) 121 password_list = [] 122 password = input('please enter your password:') 123 password_list.append(password) 124 #print(password_list) 125 with open('user_pwd.txt','a') as file : 126 for i in range(max(len(username_list),len(password_list))): 127 try: #try的思路可以學習一下,try/except 128 file.write("{}\t{}\n".format(username_list[i],password_list[i])) 129 except IndexError: 130 if len(username_list) > len(password_list): 131 file.write('{}\t\n'.format(username_list[i])) 132 else: 133 file.write('\t{}\n'.format((password_list[i]))) 134 with open('user_pwd.txt','r') as read_file: 135 print(read_file.read()) 136 ''' 137 138 139 #open的模式 140 ''' 141 mode is an optional string that specifies the mode in which the file 142 is opened. It defaults to 'r' which means open for reading in text 143 mode. Other common values are 'w' for writing (truncating the file if 144 it already exists), 'x' for creating and writing to a new file, and 145 'a' for appending (which on some Unix systems, means that all writes 146 append to the end of the file regardless of the current seek position). 147 In text mode, if encoding is not specified the encoding used is platform 148 dependent: locale.getpreferredencoding(False) is called to get the 149 current locale encoding. (For reading and writing raw bytes use binary 150 mode and leave encoding unspecified.) The available modes are: 151 ''' 152 153 154 ''' 155 ========= =============================================================== 156 Character Meaning 157 --------- --------------------------------------------------------------- 158 'r' open for reading (default) 159 'w' open for writing, truncating the file first 160 'x' create a new file and open it for writing 161 'a' open for writing, appending to the end of the file if it exists 162 'b' binary mode 163 't' text mode (default) 164 '+' open a disk file for updating (reading and writing) 165 'U' universal newline mode (deprecated) 166 ========= =============================================================== 167 168 The default mode is 'rt' (open for reading text). For binary random 169 access, the mode 'w+b' opens and truncates the file to 0 bytes, while 170 'r+b' opens the file without truncation. The 'x' mode implies 'w' and 171 raises an `FileExistsError` if the file already exists. 172 ''' 173 174 with open('song.txt','r',encoding='utf-8') as f: 175 #print(f.read()) 176 #print('====>',f.read(23)) 177 print(f.readline(3)) 178 ''' 179 for line in f: 180 #print(line) 181 print(line.rstrip()) 182 #print(line,end='') 183 ''' 184 #print(f.readlines()) 185 print(f.closed) #檢視檔案是否被關閉