06-文件操作

第6节 文件操作

在这一节中,我们将详细介绍 Python 中的文件操作。文件操作是编程中常见的任务,包括读取文件内容、写入文件、处理文件路径等。我们将学习如何打开文件、读取文件内容、写入文件以及关闭文件。

6.1 打开文件

在 Python 中,使用 open() 函数来打开文件。open() 函数需要两个参数:文件名和访问模式。

基本语法:

file_object = open(file_name, mode)

访问模式:

  • r:只读模式,默认值。如果文件不存在,会引发 FileNotFoundError
  • w:写入模式。如果文件存在,会覆盖原有内容;如果文件不存在,会创建新文件。
  • a:追加模式。如果文件存在,会在文件末尾追加内容;如果文件不存在,会创建新文件。
  • b:二进制模式。用于读写二进制文件,如图片、音频文件等。
  • t:文本模式,默认值。用于读写文本文件。
  • +:更新模式。用于读写文件。

示例:

# 打开文件,只读模式
file = open("example.txt", "r")

# 打开文件,写入模式
file = open("example.txt", "w")

# 打开文件,追加模式
file = open("example.txt", "a")

# 打开文件,二进制写入模式
file = open("image.png", "wb")
6.2 读取文件

打开文件后,可以使用多种方法读取文件内容。

读取整个文件:

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

按行读取文件:

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # 使用 strip() 去除行末的换行符

逐行读取文件:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())
6.3 写入文件

打开文件后,可以使用 write()writelines() 方法写入文件内容。

写入单行内容:

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

写入多行内容:

lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
    file.writelines(lines)

追加内容:

with open("example.txt", "a") as file:
    file.write("This is an appended line.\n")
6.4 关闭文件

在读取或写入文件后,应确保关闭文件以释放系统资源。使用 with 语句可以自动管理文件的打开和关闭。

手动关闭文件:

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

使用 with 语句自动关闭文件:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# 文件在这里自动关闭
6.5 处理文件路径

在处理文件时,经常需要处理文件路径。Python 的 ospathlib 模块提供了许多工具来处理文件路径。

使用 os 模块:

import os

# 获取当前工作目录
current_directory = os.getcwd()
print(current_directory)

# 拼接文件路径
file_path = os.path.join(current_directory, "example.txt")
print(file_path)

# 检查文件是否存在
exists = os.path.exists(file_path)
print(exists)

使用 pathlib 模块:

from pathlib import Path

# 获取当前工作目录
current_directory = Path.cwd()
print(current_directory)

# 拼接文件路径
file_path = current_directory / "example.txt"
print(file_path)

# 检查文件是否存在
exists = file_path.exists()
print(exists)

小结

通过本节的学习,你应该已经掌握了 Python 中文件操作的基本方法,包括打开文件、读取文件内容、写入文件以及关闭文件。文件操作是处理数据和存储信息的重要手段,掌握这些技能将帮助你在实际编程中更高效地处理文件。下一节我们将继续学习 Python 中的异常处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星火技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值