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")
相关推荐
Sylvia-girl3 小时前
Java——抽象类
java·开发语言
Yana.nice5 小时前
Bash函数详解
开发语言·chrome·bash
江沉晚呤时5 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
电脑能手6 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
tomorrow.hello6 小时前
Java并发测试工具
java·开发语言·测试工具
Edward-tan6 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
晓13137 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
老胖闲聊7 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
倔强青铜三7 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三7 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试