日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python文件读取方法read(size)的含义是_Python file read()方法

發布時間:2023/12/20 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python文件读取方法read(size)的含义是_Python file read()方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

描述

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

語法file.read(size)

返回值

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

使用示例

1. size省略,一次性讀完整個文件

待讀取的文件 demo.txt:2019

python代碼:data?=?open("demo.txt",?"r").read()

print(data)

執行結果:2019

2. 指定字節數讀取文件

待讀取的文件:demo.txtA?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.

假設我們只希望讀取30字節的數據:data?=?open("demo.txt",?"r").read(30)

print(data)

執行結果如下:A?thread?is?a?basic?unit?of?CP

注意事項:

1.? size為負時

當size值為負數時read()方法不會報錯,此時read()方法會讀完整個文件。

待讀取的文件:demo.txtA?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)

執行結果: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時

當size等于0時,read方法返回一個空串。data?=?open("demo.txt",?"r").read(0)

print(data)

print(type(data))

print(len(data))

執行結果:

0

為何要使用Size?

當文件過大,內存不夠一次性讀取整個文件時,就需要分批讀取文件。合理使用size可以妥善處理文件大于內存的場景。

文章來源于網絡,如有雷同,請聯系作者。

總結

以上是生活随笔為你收集整理的python文件读取方法read(size)的含义是_Python file read()方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。