赞
踩
目录
read()方法是Python的文件方法,用于读取文件中的内容,并返回文件内容的字符串。
file.read(size)
参数 | 说明 | 备注 |
size | 读取文件的字节数 | 正整数参数,可省略。省略时表示一次性读完整个文件 |
读取文件,返回字符串类型的值。
待读取的文件 demo.txt:
2019
python代码:
- data = open("demo.txt", "r").read()
- print(data)
执行结果:
2019
待读取的文件: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
当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.
当size等于0时,read方法返回一个空串。
- data = open("demo.txt", "r").read(0)
- print(data)
- print(type(data))
- print(len(data))
执行结果:
-
- <class 'str'>
- 0
当文件过大,内存不够一次性读取整个文件时,就需要分批读取文件。合理使用size可以妥善处理文件大于内存的场景。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。