標籤:lin 接受 記憶體 列表 try 方法 字元 資料 log
"""1、讀取檔案的三個方法:read()、readline()、readlines()2、三個方法均可接受一個變數用以限制每次讀取的資料量,通常不使用該變數。""""""關於read()方法:1、讀取整個檔案,將檔案內容放到一個字串變數中2、如果檔案大於可用記憶體,不可能使用這種處理"""file_object = open("test.py",‘r‘) #建立一個檔案對象,也是一個可迭代對象try: all_the_text = file_object.read() #結果為str類型 print type(all_the_text) print "all_the_text=",all_the_textfinally: file_object.close()"""關於readline()方法:1、readline()每次讀取一行,比readlines()慢得多2、readline()返回的是一個字串對象,儲存當前行的內容"""file_object1 = open("test.py",‘r‘)try: while True: line = file_object1.readline() if line: print "line=",line else: breakfinally: file_object1.close()"""關於readlines()方法:1、一次性讀取整個檔案。2、自動將檔案內容分析成一個行的列表。"""file_object2 = open("test.py",‘r‘)try: lines = file_object2.readlines() print "type(lines)=",type(lines) #type(lines)= <type ‘list‘> for line in lines: print "line=",line finally: file_object2.close()
python讀檔案的三個方法read()、readline()、readlines()詳解