python read函数_Python read()函数:读入指定长度的文本
read() 函數(shù)從當(dāng)前位置開始讀,讀出指定個(gè)數(shù)的字符。其返回值是一個(gè)字符串,表示讀取的文件內(nèi)容。
參數(shù) size 如果為正數(shù),表示最多讀出 size 個(gè)字符;如果 size 為 0,則什么也不會(huì)讀出,返回值是空字符串;如果 size 為負(fù)數(shù),表示讀出全部的內(nèi)容。size 的默認(rèn)值是 -1,表示讀出全部的內(nèi)容。
下面的例子演示了不指定 size 的值而使用默認(rèn)值 -1 的情況。
>>> fd = open("in.dat", "r") # 以只讀方式打開文件in.dat
>>> ret_str = fd.read() # 將所有文件內(nèi)容讀到ret_str,size=-1
>>> type(ret_str) # 返回值類型是字符串
>>> len(ret_str) # 字符串長(zhǎng)度為68
68
>>> print(ret_str) # 顯示文件內(nèi)容
this is input text file
it contains 3 lines
this is the end of file
>>> fd.close() # 關(guān)閉文件
下面演示指定 size,并且 size 為正數(shù)的情況。
>>> fd = open("in.dat", "r") # 以只讀方式打開文件in.dat
>>> str1 = fd.read(40) # 讀入最多40個(gè)字符,保存到str1中
>>> str2 = fd.read(40) # 讀入最多40個(gè)字符,保存到str2中
>>> len(str1) # str1包含40個(gè)字符
40
>>> len(str2) # str2包含28個(gè)字符,總共是68個(gè)字符
28
>>> print(str1+str2) # 將str1和str2連接起來,就是文件的完整內(nèi)容
this is input text file
it contains 3 lines
this is the end of file
>>> fd.close() # 關(guān)閉文件
如果到了文件的尾部,則返回空字符串。
>>> fd = open("in.dat", "r") # 以只讀方式打開文件in.dat
>>> str1 = fd.read() # 讀出全部?jī)?nèi)容
>>> str2 = fd.read() # 這時(shí)已經(jīng)到了文件的尾部
>>> type(str2) # 返回值類型是字符串
>>> len(str2) # str2的長(zhǎng)度為0,所以是空字符串
0
>>> fd.close() # 關(guān)閉文件
總結(jié)
以上是生活随笔為你收集整理的python read函数_Python read()函数:读入指定长度的文本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos安装anaconda_每天三
- 下一篇: python定义一个圆_Python-矩