Python 中处理文件是常见且重要的任务。以下是一些基础的文件处理技巧。

读取文件

使用 open() 函数可以打开一个文件,并使用 read() 方法读取内容。

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

写入文件

写入文件可以使用 open() 函数的 w 模式。

with open('example.txt', 'w') as file:
    file.write('Hello, World!')

读取和写入

同时读取和写入可以使用 r+w+ 模式。

with open('example.txt', 'r+') as file:
    file.write('New content')
    file.seek(0)  # 回到文件开头
    content = file.read()
    print(content)

文件路径

处理文件时,路径非常重要。Python 提供了 os 模块来处理文件路径。

import os

file_path = os.path.join('path', 'to', 'file.txt')

图像处理

处理图像文件时,可以使用 PIL 模块。

from PIL import Image

img = Image.open('image.png')
img.show()

更多关于 Python 文件处理的资源,请访问Python 文件处理指南

[center][https://cloud-image.ullrai.com/q/Golden_Retriever/]