Python中file.read()方法的使用示例

小編給大家分享一下Python中file.read()方法的使用示例,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

創(chuàng)新互聯(lián)專注于華安網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗(yàn)。 熱誠(chéng)為您提供華安營(yíng)銷型網(wǎng)站建設(shè),華安網(wǎng)站制作、華安網(wǎng)頁設(shè)計(jì)、華安網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造華安網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供華安網(wǎng)站排名全網(wǎng)營(yíng)銷落地服務(wù)。

在計(jì)算機(jī)中,文件包括了文檔、圖片、視頻、程序組件等,每個(gè)類型的文件都有不同的作用或功用。例如一個(gè)程序通常由主程序、動(dòng)態(tài)庫、配置文件等組成,這些也是文件,起到支持程序運(yùn)行的作用。想要使用文件,第一個(gè)操作就是打開讀取文件,那么在python如何讀取文件呢?其實(shí)使用python file read()方法。

描述

read()方法是Python的文件方法,用于讀取文件中的內(nèi)容,并返回文件內(nèi)容的字符串。

語法

file.read(size)

返回值

讀取文件,返回字符串類型的值。

 使用示例

1. size省略,一次性讀完整個(gè)文件

待讀取的文件 demo.txt:

2019

python代碼:

data = open("demo.txt", "r").read()
print(data)

執(zhí)行結(jié)果:

2019

2. 指定字節(jié)數(shù)讀取文件

待讀取的文件:demo.txt

A thread is a basic unit of CPU execution. It must depend on the process surviving. A thread is an execution context, which is what a CPU needs to execute
A list of instructions. In Python, multithreading takes longer.

假設(shè)我們只希望讀取30字節(jié)的數(shù)據(jù):

data = open("demo.txt", "r").read(30)
print(data)

執(zhí)行結(jié)果如下:

A thread is a basic unit of CP

注意事項(xiàng):

1.  size為負(fù)時(shí)

當(dāng)size值為負(fù)數(shù)時(shí)read()方法不會(huì)報(bào)錯(cuò),此時(shí)read()方法會(huì)讀完整個(gè)文件。

待讀取的文件:demo.txt

A thread is a basic unit of CPU execution. It must depend on the process surviving. A thread is an execution context, which is what a CPU needs to execute
A list of instructions. In Python, multithreading takes longer.

python腳本:

data = open("demo.txt", "r").read(-1)
print(data)

執(zhí)行結(jié)果:

A thread is a basic unit of CPU execution. It must depend on the process surviving. A thread is an execution context, which is what a CPU needs to execute
A list of instructions. In Python, multithreading takes longer.

2. size為0時(shí)

當(dāng)size等于0時(shí),read方法返回一個(gè)空串。

data = open("demo.txt", "r").read(0)
print(data)
print(type(data))
print(len(data))

執(zhí)行結(jié)果:

 
<class 'str'>
0

為何要使用Size?

當(dāng)文件過大,內(nèi)存不夠一次性讀取整個(gè)文件時(shí),就需要分批讀取文件。合理使用size可以妥善處理文件大于內(nèi)存的場(chǎng)景。

看完了這篇文章,相信你對(duì)Python中file.read()方法的使用示例有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!

當(dāng)前標(biāo)題:Python中file.read()方法的使用示例
文章URL:http://bm7419.com/article44/igdpee.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、域名注冊(cè)營(yíng)銷型網(wǎng)站建設(shè)網(wǎng)站建設(shè)、網(wǎng)站改版、響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)