网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Python中file.read()方法的使用示例-创新互联

小编给大家分享一下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.txt

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.

假设我们只希望读取30字节的数据:

data = open("demo.txt", "r").read(30)
print(data)

执行结果如下:


A thread is a basic unit of CP

注意事项:


1.  size为负时

当size值为负数时read()方法不会报错,此时read()方法会读完整个文件。

待读取的文件:demo.txt

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.

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中file.read()方法的使用示例有了一定的了解,想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


当前名称:Python中file.read()方法的使用示例-创新互联
链接分享:http://bjjierui.cn/article/ddjhsi.html

其他资讯