温馨提示×

python循环读取文件内容怎么实现

小亿
83
2024-04-15 15:31:02
栏目: 编程语言

在Python中,可以使用open()函数来打开文件,然后使用read()或者readlines()方法来读取文件的内容。接着可以使用循环来遍历文件的内容。

以下是一个例子:

# 打开文件
with open("example.txt", "r") as file:
    # 逐行读取文件内容
    for line in file:
        print(line)

如果想一次性读取文件的所有内容,可以使用read()方法:

# 打开文件
with open("example.txt", "r") as file:
    # 读取文件内容
    content = file.read()
    print(content)

另外,如果想读取指定行数的内容,可以使用readlines()方法:

# 打开文件
with open("example.txt", "r") as file:
    # 读取前5行内容
    lines = file.readlines()[:5]
    for line in lines:
        print(line)

0