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()
相关推荐
Empty_7772 小时前
编程之python基础
开发语言·python
哲Zheᗜe༘5 小时前
了解学习Python编程之python基础
开发语言·python·学习
麦麦大数据5 小时前
F024 RNN+Vue+Flask电影推荐可视化系统 python flask mysql 深度学习 echarts
python·rnn·深度学习·vue·echarts·电影推荐
Roc-xb6 小时前
ModuleNotFoundError: No module named ‘conda_token‘
开发语言·python·conda
weixin_525936336 小时前
部分Spark SQL编程要点
大数据·python·sql·spark
Xyz996_6 小时前
python编程基础知识
python
人工干智能6 小时前
Python 开发中:`.ipynb`(Jupyter Notebook 文件)和 `.py`(Python 脚本文件)
开发语言·python·jupyter
woshihonghonga6 小时前
Jupyter Notebook单元格输出换行问题解决
ide·python·jupyter
~~李木子~~7 小时前
Jupyter Notebook(ipynb)转 Python(py)文件
python·jupyter
ERROR_LESS7 小时前
【ADS-1】【python基础-1】jupyter notebook环境极简搭建
python·jupyter