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")
相关推荐
St_rive14 小时前
Page Object设计模式
java·开发语言·设计模式
CTA量化套保14 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
wp123_114 小时前
硬件元器件笔记|IPX8 防水 Type‑C 母座安费诺 124018802112A 与 TONEVEE TY48086‑24A 分析
c语言·开发语言·笔记
wuyk55514 小时前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
清水白石00815 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
Elias不吃糖15 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
luj_176815 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
TechWayfarer16 小时前
批量查IP归属地,在线API、脚本、离线库怎么选?三种方案实测对比
网络·python·网络协议·tcp/ip
七牛开发者17 小时前
为什么 Go 很适合 AI 辅助开发?
数据库·人工智能·python·elasticsearch·log4j