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()
相关推荐
Zzzz_my1 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭1 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2142 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197732 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
敏编程3 小时前
一天一个Python库:tomlkit - 轻松解析和操作TOML配置
python
2401_879693873 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
yunyun321233 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
团子和二花4 小时前
openclaw平替之nanobot源码解析(七):Gateway与多渠道集成
python·gateway·agent·智能体·openclaw·nanobot
未知鱼4 小时前
Python安全开发之简易目录扫描器(含详细注释)
开发语言·python·安全
Be1k04 小时前
推荐一款语雀知识库批量导出工具
python·gui·工具·语雀·批量导出·原创