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()
相关推荐
Blossom.11818 小时前
AI Agent的长期记忆革命:基于向量遗忘曲线的动态压缩系统
运维·人工智能·python·深度学习·自动化·prompt·知识图谱
love530love19 小时前
ComfyUI Hunyuan-3D-2 插件安装问题解决方案
人工智能·windows·python·3d·comfyui·hunyuan-3d-2·pygit2
我是一只小青蛙88819 小时前
Python Pandas 从入门到精通全指南
python
我命由我1234519 小时前
充血模型与贫血模型
java·服务器·后端·学习·架构·java-ee·系统架构
fie888920 小时前
MATLAB有限元框架程序
python·算法·matlab
时间会给答案scidag20 小时前
Spring AI Alibaba 学习day01
人工智能·学习·spring
我是小疯子6620 小时前
Python3.11.4离线安装PyInstaller全攻略
python
alphaTao20 小时前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
Fasda1234520 小时前
基于yolo11-C3k2-AKConv的太阳能电池片缺陷检测技术分享
python
风送雨20 小时前
FastAPI 学习教程 · 第4部分
学习·fastapi