当前位置:   article > 正文

Python file read方法:读取文件_python read file

python read file

目录

描述

语法

参数

返回值

使用示例

1. size省略,一次性读完整个文件

2. 指定字节数读取文件

注意事项:

1.  size为负时

2. size为0时

为何要使用Size?


描述

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

语法

file.read(size)

参数

参数说明备注
size读取文件的字节数正整数参数,可省略。省略时表示一次性读完整个文件

返回值

读取文件,返回字符串类型的值。

使用示例

1. size省略,一次性读完整个文件

待读取的文件 demo.txt:

2019

python代码:

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

执行结果:

2019

2. 指定字节数读取文件

待读取的文件:demo.txt

  1. 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
  2. A list of instructions. In Python, multithreading takes longer.

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

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

执行结果如下:

A thread is a basic unit of CP

注意事项:

1.  size为负时

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

待读取的文件:demo.txt

  1. 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
  2. A list of instructions. In Python, multithreading takes longer.

Python脚本:

  1. data = open("demo.txt", "r").read(-1)
  2. print(data)

执行结果:

  1. 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
  2. A list of instructions. In Python, multithreading takes longer.

2. size为0时

当size等于0时,read方法返回一个空串。

  1. data = open("demo.txt", "r").read(0)
  2. print(data)
  3. print(type(data))
  4. print(len(data))

执行结果:

  1. <class 'str'>
  2. 0

为何要使用Size?

当文件过大,内存不够一次性读取整个文件时,就需要分批读取文件。合理使用size可以妥善处理文件大于内存的场景。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号