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可以妥善处理文件大于内存的场景。

文章来源于网络,如有雷同,请联系作者。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值