Python3讀取文件常用方法實(shí)例分析
更新時(shí)間:2015年05月22日 11:39:09 作者:皮蛋
這篇文章主要介紹了Python3讀取文件常用方法,以實(shí)例形式較為詳細(xì)的分析了Python一次性讀取、逐行讀取及讀取文件一部分的實(shí)現(xiàn)技巧,需要的朋友可以參考下
本文實(shí)例講述了Python3讀取文件常用方法。分享給大家供大家參考。具體如下:
''''' Created on Dec 17, 2012 讀取文件 @author: liury_lab ''' # 最方便的方法是一次性讀取文件中的所有內(nèi)容放到一個(gè)大字符串中: all_the_text = open('d:/text.txt').read() print(all_the_text) all_the_data = open('d:/data.txt', 'rb').read() print(all_the_data) # 更規(guī)范的方法 file_object = open('d:/text.txt') try: all_the_text = file_object.read() print(all_the_text) finally: file_object.close() # 下面的方法每行后面有‘\n' file_object = open('d:/text.txt') try: all_the_text = file_object.readlines() print(all_the_text) finally: file_object.close() # 三句都可將末尾的'\n'去掉 file_object = open('d:/text.txt') try: #all_the_text = file_object.read().splitlines() #all_the_text = file_object.read().split('\n') all_the_text = [L.rstrip('\n') for L in file_object] print(all_the_text) finally: file_object.close() # 逐行讀 file_object = open('d:/text.txt') try: for line in file_object: print(line, end = '') finally: file_object.close() # 每次讀取文件的一部分 def read_file_by_chunks(file_name, chunk_size = 100): file_object = open(file_name, 'rb') while True: chunk = file_object.read(chunk_size) if not chunk: break yield chunk file_object.close() for chunk in read_file_by_chunks('d:/data.txt', 4): print(chunk)
輸出如下:
hello python hello world b'ABCDEFG\r\nHELLO\r\nhello' hello python hello world ['hello python\n', 'hello world'] ['hello python', 'hello world'] hello python hello worldb'ABCD' b'EFG\r' b'\nHEL' b'LO\r\n' b'hell' b'o'
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python的staticmethod與classmethod實(shí)現(xiàn)實(shí)例代碼
這篇文章主要介紹了python的staticmethod與classmethod實(shí)現(xiàn)實(shí)例代碼,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02Python連接PostgreSQL數(shù)據(jù)庫(kù)的方法
大家應(yīng)該都有所了解,python可以操作多種數(shù)據(jù)庫(kù),諸如SQLite、MySql、PostgreSQL等,這里不對(duì)所有的數(shù)據(jù)庫(kù)操作方法進(jìn)行贅述,只針對(duì)目前項(xiàng)目中用到的PostgreSQL做一下簡(jiǎn)單介紹,主要是Python連接PostgreSQL數(shù)據(jù)庫(kù)的方法。有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-11-11Django集成MongoDB實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了Django集成MongoDB實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12python的即時(shí)標(biāo)記項(xiàng)目練習(xí)筆記
這篇文章主要介紹了python的即時(shí)標(biāo)記項(xiàng)目練習(xí)筆記,本文是閱讀《python基礎(chǔ)教程》一書的動(dòng)手實(shí)踐項(xiàng)目,需要的朋友可以參考下2014-09-09Python定時(shí)發(fā)送天氣預(yù)報(bào)郵件代碼實(shí)例
這篇文章主要介紹了Python定時(shí)發(fā)送天氣預(yù)報(bào)郵件代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09