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()
相关推荐
是多巴胺不是尼古丁9 小时前
期末java复习--string
java·开发语言·python
garmin Chen9 小时前
从 Transformer 到 Agent:大模型技术全景解析
java·人工智能·python·深度学习·transformer
没有钱的钱仔9 小时前
pytorch_cuda安装
人工智能·pytorch·python
Full Stack Developme9 小时前
Apache Tika 教程
java·开发语言·python·apache
笨笨没好名字9 小时前
Leetcode刷题python版第一周
python·算法·leetcode
Cthy_hy9 小时前
斯特林数:组合划分的递归经典,一二两类全解
python·算法·斯特林数
青春:一叶知秋10 小时前
【Python】python基本语法和使用
开发语言·python
SilentSamsara10 小时前
向量数据库实战:Chroma/Milvus/Qdrant 选型与语义搜索应用
开发语言·数据库·人工智能·python·青少年编程·milvus
沪漂阿龙10 小时前
Embedding:文本怎么变成向量?语义检索为什么能工作?
人工智能·python·embedding
生信碱移10 小时前
Vscode 连接 ipynb 选择内核无法自动显示 conda 环境对应的 python
服务器·人工智能·经验分享·vscode·python