知行编程网知行编程网  2022-10-20 07:00 知行编程网 隐藏边栏  4 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python file read()方法的相关知识,包括readall,以及Python file这些编程知识,希望对大家有参考作用。


Python文件读取()方法

在计算机中,文件包括文档、图片、视频、程序组件等。每种类型的文件都有不同的作用或功能。例如,一个程序通常由主程序、动态库、配置文件等组成,它们也是文件,起到支持程序运行的作用。如果要使用文件,首先操作是打开和读取文件,那么在python中如何读取文件呢?实际使用python文件read()方法。




描述


read() 方法是 Python 的 file 方法,它读取文件的内容并返回文件内容的字符串。



语法

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))

执行结果:

 
<class 'str'>
0



为何要使用Size?

当文件太大,内存不足以一次读取整个文件时,需要分批读取文件。合理使用size可以很好的处理文件大于内存的场景。


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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享