python学习笔记----文件操作(八)

一、 open() 函数

  • 在 Python 中,处理文件包括读取和写入操作,是通过使用内置的 open() 函数来实现的。

语法: open(file, mode="r", encoding="utf-8")

  • file: 文件路径。
  • mode: 文件打开模式:
    'r':读取模式(默认)。
    'w':写入模式,先清空文件。
    'a':追加模式,写入到文件现有内容之后。
    'b':二进制模式。
    '+':读写模式(可以添加到其他模式中使用,如 'r+')。
  • encoding: 文本文件的编码方式,如 'utf-8'。

二、读取文件

  • 读取文件通常使用 'r' 模式。你可以一次读取文件的全部内容,或者逐行读取。

示例:

python 复制代码
# 打开文件
file = open('example.txt', 'r', encoding='utf-8')
# 读取文件内容
content = file.read()
print(content)
# 关闭文件
file.close()

三、写入文件

  • "w"写入模式,会覆盖已存在的文件。
python 复制代码
# 打开文件进行写入,如果文件存在,则覆盖原有内容
file = open('C:\\Users\\ABC\\Desktop\\example.txt', 'w', encoding='utf-8')
# 写入内容到文件
file.write("Hello, Python!\n")
file.write("Adding another line.")
# 关闭文件
file.close()

四、逐行读取文件

这个例子展示了如何打开一个文件,逐行读取文件的内容,然后关闭文件:

python 复制代码
# 打开文件
file = open('C:\\Users\\ABC\\Desktop\\example.txt', 'r', encoding='utf-8')
# 逐行读取文件
for line in file:
    print(line.strip())  # strip() 用于去掉行末的换行符
# 关闭文件
file.close()
相关推荐
cup111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi003 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵5 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf6 小时前
Agent 流程编排
后端·python·agent
copyer_xyf6 小时前
Agent RAG
后端·python·agent
copyer_xyf6 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf6 小时前
Agent 记忆管理
后端·python·agent
星云穿梭21 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏