Python3讀取文件常用方法實(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)容放到一個大字符串中:
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程序設(shè)計有所幫助。
相關(guān)文章
使用Python實(shí)現(xiàn)正態(tài)分布、正態(tài)分布采樣
今天小編就為大家分享一篇使用Python實(shí)現(xiàn)正態(tài)分布、正態(tài)分布采樣,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
基于Python實(shí)現(xiàn)MUI側(cè)滑菜單a標(biāo)簽跳轉(zhuǎn)
這篇文章主要介紹了基于Python實(shí)現(xiàn)MUI側(cè)滑菜單a標(biāo)簽跳轉(zhuǎn),mui最接近原生APP體驗(yàn)的高性能前端框架,MUI側(cè)滑常見的場景有下拉刷新,側(cè)滑抽屜,側(cè)滑刪除,側(cè)滑返回以及側(cè)滑菜單等等,下面來看看文章內(nèi)容詳細(xì)的介紹,需要的朋友可以參考一下2021-11-11
關(guān)于Python使用logging庫進(jìn)行有效日志管理的方法詳解
在開發(fā)大型軟件或處理復(fù)雜問題時,我們經(jīng)常需要一種方法來記錄和跟蹤程序的運(yùn)行狀態(tài),Python 提供了一個名為 logging 的標(biāo)準(zhǔn)庫,可以幫助我們更好地完成這項(xiàng)任務(wù),在這篇文章中,我們將介紹如何使用 Python 的 logging 庫進(jìn)行日志記錄2023-06-06
Python實(shí)現(xiàn)求取表格文件某個區(qū)域內(nèi)單元格的最大值
這篇文章主要介紹基于Python語言,基于Excel表格文件內(nèi)某一列的數(shù)據(jù),計算這一列數(shù)據(jù)在每一個指定數(shù)量的行的范圍內(nèi)(例如每一個4行的范圍內(nèi))的區(qū)間最大值的方法,需要的朋友可以參考下2023-08-08

