Python基础知识:整理9 文件的相关操作

1 文件的打开

python 复制代码
# open() 函数打开文件
# open(name, mode, encoding)
"""
    name:  文件名(可以包含文件所在的具体路径)
    mode:  文件打开模式
    encoding:  可选参数,表示读取文件的编码格式
"""

2 文件的读取

文件的打开模式为 r

以下为需要读的文件中的内容

2.1 读取文件-read(num)

复制代码
num 表示要从文件中读取的数据的长度(单位是字节),如果没有传入num, 那么就表示读取文件中的所有数据
python 复制代码
file = open("txt/test.txt", "r", encoding="utf-8")

# 1.读取文件-read(num)
data = file.read()
print(data)

2.2 读取文件-readlines()

复制代码
读取文件中每一行,返回一个列表,其中每一行的数据为列表中的一个元素
python 复制代码
file = open("txt/test.txt", "r", encoding="utf-8")

# 2. 读取文件-readlines()
data = file.readlines()
print(data)

2.3 读取文件-readline()

复制代码
读取文件中的一行数据
python 复制代码
file = open("txt/test.txt", "r", encoding="utf-8")

# 3. 读取文件-readline() 
data1 = file.readline()
data2 = file.readline()
data3 = file.readline()

print(f"第一行的数据是{data1}")
print(f"第二行的数据是{data2}")
print(f"第三行的数据是{data3}")

2.4 for循环读取文件行

python 复制代码
file = open("txt/test.txt", "r", encoding="utf-8")

# 4. for循环读取文件行
for line in file:
    print(line, end="")

2.5 文件关闭

python 复制代码
file.close()

2.6 with open 语法操作文件

复制代码
这种方法可以自动关闭文件,就不用手动关闭文件了
python 复制代码
with open("txt/test.txt", "r", encoding="utf-8") as file:
     list = file.readlines()
print(list)

3 文件的写入操作

文件的打开模式为 w

3.1 打开一个不存在的文件 -> 创建文件

python 复制代码
# 1.打开一个不存在的文件  创建
fw1 = open("txt/write_test.txt", "w", encoding="UTF-8")
fw1.write("hello girl!")  # 将内容写入到内存中

# flush 刷新
fw1.flush()     # 将内存中积攒的内容,写入到磁盘文件中

# 关闭文件
fw1.close()    #  关闭文件,释放资源, 内置flush方法,会自动刷新,写close()方法,可以省略flush()方法

3.2 打开一个存在的文件 -> 覆盖原本内容

python 复制代码
fw1 = open("txt/write_test.txt", "w", encoding="UTF-8")
fw1.write("hello boy!")  # 将内容写入到内存中

# flush 刷新
fw1.flush()     # 将内存中积攒的内容,写入到磁盘文件中

# 关闭文件
fw1.close()

4 文件的追加操作

文件的打开模式为 a

4.1 打开一个存在的文件 -> 追加到原本内容的后面

python 复制代码
# 1.打开一个存在的文件    追加到原本内容的后面
fw1 = open("txt/add_test.txt", "a", encoding="UTF-8")
fw1.write("I love you")  # 将内容写入到内存中

# flush 刷新
fw1.flush()     # 将内存中积攒的内容,写入到磁盘文件中

# 关闭文件
fw1.close()

4.2 打开一个不存在的文件 -> 创建文件

python 复制代码
fw1 = open("txt/add_test.txt", "a", encoding="UTF-8")
fw1.write("hello boy!")  # 将内容写入到内存中

# flush 刷新
fw1.flush()     # 将内存中积攒的内容,写入到磁盘文件中

# 关闭文件
fw1.close()
相关推荐
傻啦嘿哟7 分钟前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
2501_933670798 分钟前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql
2601_9620776017 分钟前
python Dejavu库快速识别音频指纹实例探究
python·音乐识别·dejavu库·音频指纹识别·实例探究
科技苑34 分钟前
如何用Python编程实现一个简单的Web爬虫?
人工智能·python
dayDayupbetter1 小时前
Visual C++ 2010安装与使用高手秘籍
python
隐擎fox1 小时前
深入理解网络传输层安全:TLS 指纹识别(JA3/JA4)原理与 Python 协议层检测实战
爬虫·python·网络协议·安全·网络安全·https
医疗信息化王工1 小时前
DataForge:基于 Python 的数据库批量导出 Excel 工具——从架构到部署的全流程实战
数据库·python·excel
小玮看世界2 小时前
[Python]从合并区间到传感器融合区:合并区间在传感器区域融合的实际落地
开发语言·python
Java陈序员3 小时前
轻量运维面板!一款现代化的服务器控制面板工具!
运维·服务器·python·react.js·github
2601_962097363 小时前
1. 使用 C 或 C++ 扩展 Python
python·api·c·引用计数·扩展模块