【Python基础编程198 ● 文件/文件夹操作 ● 读取文件的4种方式】


---------Python基础编程---------

Author : AI菌


 

【内容讲解】

Python读取文件的4种方式,包括read()、read(字节数)、readlines()、readline()方式。

0. read() :一次读取所有,返回str
1. read(字节数) : 一次读几个字节
2. readlines() :按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素
3.  readline() : 一次读取文件的一行, 返回的是一个str

【代码实现】

# 0.read()方式,一次读取所有,返回str
file0 = open("a.txt", "r")
content = file0.read()
print(type(content))  # <class 'str'>
print(content)
file0.close()

# 1.read(字节数)方式,一次读几个字节
file1 = open("a.txt", "r")
# 一次读取2个字节数据
content = file1.read(2)
print(type(content))  # <class 'str'>
print(content)
# 从上次读取的位置继续读取剩下的所有的数据
content = file1.read()
print(content)
file1.close()

# 2. readlines()方式,按照行的方式把整个文件中的内容进行一次性读取,
# # 并且返回的是一个列表,其中每一行的数据为一个元素
file2 = open("a.txt", "r")
content = file2.readlines()
print(type(content))  # <class 'list'>
print(content)  # ['python
', 'java
', 'AI']
file2.close()

i = 1
for temp in content:
    print(f"{i}:{temp}")
    i += 1
file2.close()

# 3.readline方式,一次读取文件的一行,返回的是一个str
file3 = open("a.txt", "r")
content = file3.readline()
print(type(content))  # <class 'str'>
print("1:%s" % temp)

content = file3.readline()
print(type(content))  # <class 'str'>
print("2:%s" % temp)
file3.close()
View Code

【往期精彩】

1.【Python基础编程195 ● 读取文件的4种方式】
2.【Python基础编程196 ● 读取文件的4种方式】
2.【Python基础编程197 ● 读取文件的4种方式】
4.【Python基础编程198 ● 读取文件的4种方式】
5.【Python基础编程199 ● 读取文件的4种方式】
6.【Python基础编程200 ● 读取文件的4种方式】
7.【Python基础编程201 ● 读取文件的4种方式】

【加群交流】

原文地址:https://www.cnblogs.com/hezhiyao/p/13373745.html