Python3讀取文件常用方法實例分析
更新時間:2015年05月22日 11:39:09 作者:皮蛋
這篇文章主要介紹了Python3讀取文件常用方法,以實例形式較為詳細的分析了Python一次性讀取、逐行讀取及讀取文件一部分的實現(xiàn)技巧,需要的朋友可以參考下
本文實例講述了Python3讀取文件常用方法。分享給大家供大家參考。具體如下:
'''''
Created on Dec 17, 2012
讀取文件
@author: liury_lab
'''
# 最方便的方法是一次性讀取文件中的所有內(nèi)容放到一個大字符串中:
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'
希望本文所述對大家的Python程序設計有所幫助。
相關文章
python的staticmethod與classmethod實現(xiàn)實例代碼
這篇文章主要介紹了python的staticmethod與classmethod實現(xiàn)實例代碼,分享了相關代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02
Python連接PostgreSQL數(shù)據(jù)庫的方法
大家應該都有所了解,python可以操作多種數(shù)據(jù)庫,諸如SQLite、MySql、PostgreSQL等,這里不對所有的數(shù)據(jù)庫操作方法進行贅述,只針對目前項目中用到的PostgreSQL做一下簡單介紹,主要是Python連接PostgreSQL數(shù)據(jù)庫的方法。有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-11-11

