Python文件操作命令

文件操作

我知道你最近很累,是那种看不见的、身体上和精神上的疲惫感,但是请你一定要坚持下去。就算无人问津也好,技不如人也好,千万别让烦躁和焦虑毁了你的热情和定力。别贪心,我们不可能什么都有,也别灰心,我们不可能什么都没有。

在 Python 中,打开文件时需要指定打开文件的模式。常见的文件打开模式包括:

  1. 'r' :读取模式。默认模式,用于读取文件内容。如果文件不存在,则会引发 FileNotFoundError 错误。

  2. 'w':写入模式。如果文件不存在,则创建文件;如果文件已存在,则先清空文件内容,然后写入新内容。

  3. 'a':追加模式。用于在文件末尾添加新内容,而不会影响原有内容。如果文件不存在,则创建文件。

打开文件并读取内容

python 复制代码
with open("./data/example.txt", "r",encoding="utf-8") as file:
    content = file.read()
    print(content)

写入内容到文件

python 复制代码
with open("./data/example.txt", "w") as file:
    file.write("Hello, World!")

逐行读取文件内容

python 复制代码
with open("./data/example.txt", "r") as file:
    for line in file:
        print(line)

追加内容到文件

python 复制代码
with open("./data/example.txt", "a") as file:
    file.write("\nAppending new line!")

文件重命名

python 复制代码
import os
os.rename("./data/example.txt", "./data/new_example.txt")

文件删除

python 复制代码
import os
os.remove("./data/example.txt")

检查文件是否存在

python 复制代码
import os
if os.path.exists("./data/example.txt"):
    print("文件存在")
else:
    print("文件不存在")

创建文件目录

python 复制代码
import os
os.mkdir("example_directory")

删除文件目录

python 复制代码
import os
os.rmdir("example_directory")
相关推荐
czhc1140075663几秒前
Linux 76 rsync
linux·运维·python
软件黑马王子25 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon27 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉31 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
Da_秀35 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte41 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
m0_625686551 小时前
day53
python
Real_man1 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
站大爷IP2 小时前
Python文件操作的"保险箱":with语句深度实战指南
python
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程