iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python 点滴记录8:文件操作rea
  • 391
分享到

python 点滴记录8:文件操作rea

点滴操作文件 2023-01-31 02:01:59 391人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

python读取文件内容时,有三种方法:read()、readline()和readlines()这三种方法区别如下:read(...)     read([size]) -> read at most size bytes, ret

python读取文件内容时,有三种方法:read()、readline()和readlines()

这三种方法区别如下:

read(...)
    read([size]) -> read at most size bytes, returned as a string.
    
    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.

简单说,read()方法若不指定读取字节数,默认读取全部文件内容(所有文件内容存在内存),生成一个字符串

  

readline(...)
      readline([size]) -> next line from the file, as a string.
    
      Retain newline.  A non-negative size argument limits the maximum
      number of bytes to return (an incomplete line may be returned then).
      Return an empty string at EOF.

简单说,readline()方法若不指定读取的字节数,默认每次读取一行,生成一个字符串。每执行一次readline()方法,则读取文件的一行。可用循环来完成整个文件的读取。


readlines(...)
    readlines([size]) -> list of strings, each a line from the file.
    
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

简单说,readlines()方法若不指定读取的字节数,默认读取整个文件内容(所有文件内容存在内存),生成一个列表。列表中的每个元素是文件的一行。可用for循环打印每一行。


注:对于很大的文件,不适合使用read()和readlines()方法。因为这两种方法都是一次性将文件内容读取完放入内存。

--结束END--

本文标题: python 点滴记录8:文件操作rea

本文链接: https://www.lsjlt.com/news/186440.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作