【Python】文件操作 ② ( 文件操作 | 读取文件 | read 函数 | readline 函数 | readlines 函数 )





一、读取文件



在 Python 中 , 操作文件 的流程如下 :

  • 打开文件
  • 读写文件
  • 关闭文件

1、read 函数


文件打开后 , 可以获得一个 _io.TextIOWrapper 类型的文件对象 ;

调用 文件对象#read 函数 , 可以 读取文件对象中的数据 ;

# 读取文件中所有数据
文件对象.read()

# 读取文件中 num 字节数据
文件对象.read(num)

read 函数默认可以读取文件中的所有数据 ,

如果为 read 函数传入一个数字作为参数 , 那么读取指定字节的数据 ;


如果调用多次 read 函数 , 后面的 read 会在前面的 read 函数基础上进行读取 ;


2、readline 函数


调用 文件对象#readline 函数 可以 一次读取 文件 一行数据 ,

返回结果是一个字符串 ;


3、readlines 函数


调用 文件对象#readlines 函数 可以 一次性读取 文件 所有数据 ,

返回结果是一个列表 ,

列表中的每个元素对应文件中的一行元素 ;





二、代码示例 - 读取文件



下面代码中读取的文件 file.txt 内容如下 :

Hello World
Tom
Jerry

在这里插入图片描述


1、代码示例 - read 函数读取文件 10 字节内容


代码示例 :

"""
文件操作 代码示例
"""

file = open("file.txt", "r", encoding="UTF-8")
print(type(file))  # <class '_io.TextIOWrapper'>

print("read 函数读取文件 10 字节内容: ")

# 读取文件 10 字节内容
print(file.read(10))

执行结果 :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函数读取文件 10 字节内容: 
Hello Worl

Process finished with exit code 0

2、代码示例 - read 函数读取文件所有内容


代码示例 :

"""
文件操作 代码示例
"""

file = open("file.txt", "r", encoding="UTF-8")
print(type(file))  # <class '_io.TextIOWrapper'>

print("read 函数读取文件所有内容: ")

# 读取文件所有内容
lines = file.readlines()

print(lines)

for line in lines:
    print(line)

执行结果 :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函数读取文件所有内容: 
['Hello World\n', 'Tom\n', 'Jerry']
Hello World

Tom

Jerry

Process finished with exit code 0

3、代码示例 - readline 函数读取文件一行内容


代码示例 :

"""
文件操作 代码示例
"""

file = open("file.txt", "r", encoding="UTF-8")
print(type(file))  # <class '_io.TextIOWrapper'>

print("read 函数读取文件一行内容: ")

# 读取文件所有内容
line = file.readline()

print(line)

执行结果 :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函数读取文件一行内容: 
Hello World


Process finished with exit code 0


4、代码示例 - readlines 函数读取文件所有内容


代码示例 :

"""
文件操作 代码示例
"""

file = open("file.txt", "r", encoding="UTF-8")
print(type(file))  # <class '_io.TextIOWrapper'>

print("read 函数读取文件所有内容: ")

# 读取文件所有内容
lines = file.readlines()

for line in lines:
    print(line)

执行结果 :

D:\001_Develop\022_Python\Python39\python.exe D:/002_Project/011_Python/HelloPython/Hello.py
<class '_io.TextIOWrapper'>
read 函数读取文件所有内容: 
Hello World

Tom

Jerry

Process finished with exit code 0

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/han1202012/article/details/131289770
今日推荐