python讀檔案的三個方法read()、readline()、readlines()詳解

來源:互聯網
上載者:User

標籤: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()詳解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.