在 Python 中,文件读取是一个基础且重要的操作。无论是读取配置文件、日志文件还是用户输入,了解如何正确地读取文件都是必不可少的。下面将介绍几种常见的文件读取方法。

1. 打开文件

首先,我们需要使用 open() 函数来打开文件。这个函数需要两个参数:文件路径和模式。

with open('example.txt', 'r') as file:
    # 文件操作

在上面的代码中,'example.txt' 是文件的路径,'r' 表示以只读模式打开文件。

2. 读取文件内容

一旦文件被打开,我们可以使用以下方法读取内容:

2.1 读取全部内容

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

2.2 逐行读取

with open('example.txt', 'r') as file:
    for line in file:
        print(line, end='')

2.3 读取指定行

with open('example.txt', 'r') as file:
    line = file.readline()
    print(line, end='')

3. 图片读取

在 Python 中,我们可以使用 PIL 库来读取图片文件。

from PIL import Image

img = Image.open('example.jpg')
img.show()

4. 扩展阅读

更多关于 Python 文件操作的教程,请参考Python 文件操作教程

[center]example