文件的读取


1、read方法

# 读取文件中所有数据
with open('test.txt', 'r', encoding='utf-8') as file:
    x = file.read()
    print(x)

# 读取文件中前10个数据
with open('test.txt', 'r', encoding='utf-8') as file:
    x = file.read(10)
    print(x)

2、for循环

# 使用for循环逐行遍历文件
with open('test.txt', 'r', encoding='utf-8') as file:
    for x in file:
        print(x)

3、readline方法

# 读取第1行所有数据
with open('test.txt', 'r', encoding='utf-8') as file:
    line = file.readline()
    print(line)

# 读取第1行前3个数据
with open('test.txt', 'r', encoding='utf-8') as file:
    line = file.readline(3)
    print(line)

# 读取前3行所有数据
with open('test.txt', 'r', encoding='utf-8') as file:
    line = file.readline()
    print(line)
    line = file.readline()
    print(line)
    line = file.readline()
    print(line)

4、readlines方法

# 读取所有行数据并返回列表
with open('test.txt', 'r', encoding='utf-8') as file:
    line = file.readlines()
    print(line)

# 指定的数据长度不超过第1行会读取第1行整行
# 指定的数据长度超过第1行且不超过第2行会读取第1行和第2行整行
# 以此类推
with open('test.txt', 'r', encoding='utf-8') as file:
    line = file.readlines(25)
    print(line)

results matching ""

    No results matching ""