2025年4月7日 星期一 乙巳(蛇)年 正月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python read()函数:读入指定长度的文本

时间:10-01来源:作者:点击数:38

read() 函数从当前位置开始读,读出指定个数的字符。其返回值是一个字符串,表示读取的文件内容。

参数 size 如果为正数,表示最多读出 size 个字符;如果 size 为 0,则什么也不会读出,返回值是空字符串;如果 size 为负数,表示读出全部的内容。size 的默认值是 -1,表示读出全部的内容。

下面的例子演示了不指定 size 的值而使用默认值 -1 的情况。

  • >>> fd = open("in.dat", "r") # 以只读方式打开文件in.dat
  • >>> ret_str = fd.read() # 将所有文件内容读到ret_str,size=-1
  • >>> type(ret_str) # 返回值类型是字符串
  • <class 'str'>
  • >>> len(ret_str) # 字符串长度为68
  • 68
  • >>> print(ret_str) # 显示文件内容
  • this is input text file
  • it contains 3 lines
  • this is the end of file
  • >>> fd.close() # 关闭文件

下面演示指定 size,并且 size 为正数的情况。

  • >>> fd = open("in.dat", "r") # 以只读方式打开文件in.dat
  • >>> str1 = fd.read(40) # 读入最多40个字符,保存到str1中
  • >>> str2 = fd.read(40) # 读入最多40个字符,保存到str2中
  • >>> len(str1) # str1包含40个字符
  • 40
  • >>> len(str2) # str2包含28个字符,总共是68个字符
  • 28
  • >>> print(str1+str2) # 将str1和str2连接起来,就是文件的完整内容
  • this is input text file
  • it contains 3 lines
  • this is the end of file
  • >>> fd.close() # 关闭文件

如果到了文件的尾部,则返回空字符串。

  • >>> fd = open("in.dat", "r") # 以只读方式打开文件in.dat
  • >>> str1 = fd.read() # 读出全部内容
  • >>> str2 = fd.read() # 这时已经到了文件的尾部
  • >>> type(str2) # 返回值类型是字符串
  • <class 'str'>
  • >>> len(str2) # str2的长度为0,所以是空字符串
  • 0
  • >>> fd.close() # 关闭文件

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门