Python(七)- 文件操作

news/2024/9/29 4:49:47 标签: python

目录

文件操作

打开文件

读数据

写数据

关闭文件

文件读写实例

文件写

文件读

读数据类型

备份文件

os模块

目录的具体操作


文件操作

在Python中操作文件记录信息的步骤:

python">(1)打开文件,或新建一个文件; open()
(2)读取或写入数据内容; read() / write()
(3)关闭文件。 close()

打开文件

函数名含义
open(name, mode)创建一个新文件或打开一个已经存在的文件,name指的是文件名,mode指的是访问模式。

常见的mode访问模式有:

模式描述
r以读数据的方式打开文件,这是默认模式,可以省略。
rb以读二进制原始数据的方式打开文件。
w以写数据的方式打开文件。如果文件已存在,则打开文件写入数据是会覆盖原有内容。如果文件不存在,则创建新文件。
wb以写二进制原始数据的方式打开文件。
a使用追加内容形式,打开一个文件。通常用于写数据,此时会把新内容写入到已有内容后。

说明:

(1)访问模式r表示read,即读;

(2)访问模式w表示write,即写。

读数据

该文件必须存在

函数名含义
read()从某文件中,一次性读完整的数据。
readlines()按行的方式把文件中的完整内容进行一次性读取,并返回一个列表。
readline()一行一行读文件中的数据内容。

说明:

当访问模式有r时,可以读数据。

写数据

函数名含义
write(seq)给某文件写数据。

说明:

(1)当访问模式有w时,可以写数据;

(2)当使用访问模式a时,用于追加数据内容,也可以写入数据。

关闭文件

函数名含义
close()关闭文件。

文件读写实例

文件写

python"># 1 普通写
# # 1.1 打开文件
writer = open("./file/a_hello.txt", "w") # 默认写, 覆盖效果
#
# # 1.2 操作文件
writer.write("hello")
writer.write("\nworld")
#
# # 1.3 关闭文件
writer.close()

# 2 写 追加
# # 2.1 打开文件
writer = open("./file/a_hello.txt", "a") # a, append 追加
#
# # 2.2 操作文件
writer.write("\nhello python")
writer.write("\nhello hadoop")

# # 2.3 关闭文件
writer.close()

# 3 写 中文
# # 3.1 打开文件
writer = open("./file/a_hello.txt", "w", encoding="utf-8") # a, append 追加
#
# # 3.2 操作文件
writer.write("黑马程序员")
writer.write("\n传智播客")
#
# # 3.3 关闭文件
writer.close()

# 4 简化
with open("./file/b_hello.txt", "w", encoding="utf-8") as writer:
    writer.write("黑马程序员")
    writer.write("\n传智播客")
    writer.write("\n字节跳动")

文件读

python"># # 1.2 读取文件
content = reader.read()
print(content)
#
# # 1.3 关闭文件
reader.close()

# 2 读 中文
# # 2.1 打开文件
reader = open("./file/b_hello.txt", 'r', encoding='utf-8')
#
# # 2.2 读取文件
content = reader.read()
print(content)
#
# # 2.3 关闭文件
reader.close()

读数据类型

函数名含义
readlines()按行的方式把文件中的完整内容进行一次性读取,并返回一个列表。
readline()一行一行读文件中的数据内容。
read()从某文件中,一次性读完整的数据。
python"># 3 读 简化
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader:
    content = reader.read()
    print(content)

# 4 读 一次读取所有的行
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader:
    lines = reader.readlines()
    print(lines)
    print(type(lines))
    print("-" * 50)

    for line in lines:
        print(line, end='')

# 5 读 一次读取一行
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader:
    line = reader.readline()
    print(line, end="")
    print(type(line))
    print(len(line))
    print("-" * 50)

    line = reader.readline()
    print(line, end="")
    print(type(line))
    print(len(line))
    print("-" * 50)

    line = reader.readline()
    print(line, end="")
    print(type(line))
    print(len(line))
    print("-" * 50)

    line = reader.readline()
    print(line, end="")
    print(type(line))
    print(len(line))
    print("-" * 50)

    line = reader.readline()
    print(line, end="")
    print(type(line))
    print(len(line))
    print("-" * 50)

# 5.2 读 优化 一次读取一行
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader:
    while True:
        line = reader.readline()

        if len(line) == 0:
            break

        print(line, end='')

备份文件

将原文件的数据内容进行重新写入到另一个新文件中。

python"># 目标6: r vs rb 的区别
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader:
    content = reader.read()
    print(content)
    print(type(content))

print("-" * 100)

with open("./file/b_hello.txt", 'rb') as reader:
    content = reader.read()
    print(content)
    print(type(content))

# 目标7: 备份
with open("./file/b_hello.txt", 'r', encoding='utf-8') as reader, open("./file/b_hello[备份].txt", 'w', encoding='utf-8') as writer:
    # 合并式
    # writer.write(reader.read())

    # 分解式
    content = reader.read()
    writer.write(content)

with open("./file/c.mp4", 'rb') as reader, open("./file/c[备份].mp4", 'wb') as writer:
    # 合并式
    # writer.write(reader.read())

    # 分解式
    content = reader.read()
    writer.write(content)

os模块

Python中的os模块包含有操作系统所具备的功能,如查看路径、创建目录、显示文件列表等。

# 导入os模块
import os

在Python中,os模块的常用函数分为两类:

(a)通过os.path调用的函数

(b)通过os直接调用的函数

在Python的os模块中,通过os.path常用函数:

函数名含义
exists(pathname)用来检验给出的路径是否存在。
isfile(pathname)用来检验给出的路径是否是一个文件。
isdir(pathname)用来检验给出的路径是否是一个目录。
abspath(pathname)获得绝对路径。
join(pathname,name)连接目录与文件名或目录。
basename(pathname)返回单独的文件名。
dirname(pathname)返回文件路径。
python"># (1)在某目录下手动新建day05/file目录与day05/file/hello.txt文件;
# (2)判断file/hello.txt是否存在、是否是文件、是否是目录、获取绝对路径名、获取单独的文件名;
# (3)执行程序,观察效果。
import os
#
# path = "./file/a_hello.txt"
path = "D:/0000_资料分享/01_大数据/07_python/代码/pythonProject3/pythonProject_2/day05/file/a_hello.txt"
#
print(os.path.exists(path)) # True
print(os.path.isfile(path)) # True
print(os.path.isdir(path)) # False
#
print(os.path.abspath(path)) # D:\0000_资料分享\01_大数据\07_python\代码\pythonProject3\pythonProject_2\day05\file\a_hello.txt
print(os.path.basename(path)) # a_hello.txt
print(os.path.dirname(path)) # ./file

import os

# (1)获取当前工作目录;
print(os.getcwd()) # D:\0000_资料分享\01_大数据\07_python\代码\pythonProject3\pythonProject_2\day05

# (2)获取day05/file下的文件或目录列表信息;
path = "./file"
result = os.listdir(path)
print(result)
print(type(result))
for e in result:
    print(e)

# (3)思考:若要在file下新建hello/world/python目录,该怎么做呢?
path = "./file/hello/world/python"

if not os.path.exists(path):
    os.makedirs(path)

目录的具体操作

函数名含义
getcwd()获得当前工作目录,即当前Python脚本工作的目录路径。
system(name)运行shell命令。
listdir(path)返回指定目录下的所有文件和目录名,即获取文件或目录列表。
mkdir(path)创建单个目录。
makedirs(path)创建多级目录。
remove(path)删除一个文件。
rmdir(path)删除一个目录。
rename(old, new)重命名文件。

http://www.niftyadmin.cn/n/5682402.html

相关文章

Java: 数据类型与变量和运算符

目录 一 .字面常量 二.数据类型 三.变量 1.语法格式 2.整型变量 (1).整型变量 (2). 长整型变量 (3).短整型变量 (4).字节型变量 3.浮点型变量 (1).双精度浮点型 (2).单精度浮点型 4.字符型变量 5.布尔型变量 四.类型转换 1.自动类型转换(隐式) 2.强制类型转换(…

docker笔记_数据卷、挂载

docker数据存储 概述数据卷(Volumes)特点操作 绑定挂载(Bind Mounts)内存挂载(tmpfs)总结 概述 docker官方文档 镜像构建过程中,所产生的layer都是只读层,只有在创建容器时才会生成…

Vue 3 文件编译流程详解与 Babel 的使用

文章目录 一、背景二、结论三、vitejs/plugin-vue 插件调试前物料准备vuePlugin 入口buildStart 方法transform 方法 四、vue/compiler-sfc 核心包parse 方法compileScript、rewriteDefault 方法compileTemplate 方法 五、整体架构六、总结参考资料 一、背景 最近正在研究 rea…

STM32F745IE 能进定时器中断,无法进主循环

当你遇到STM32F745IE这类问题,即能够进入定时器中断但无法进入主循环(main() 函数中的循环),可能的原因和解决方法包括以下几个方面: 检查中断优先级和嵌套: 确保没有其他更高优先级的中断持续运行并阻止了主循环的执行。使用调试工具查看中断的进入和退出情况。检查中断…

用Flutter几年了,Flutter每个版本有什么区别?

用Flutter几年了,你知道Flutter每个版本有什么区别吗?不管是学习还是面试我们可能都需要了解这个信息。 Flutter 每个版本的用法基本都是一样的,每隔几天或者几周就会更新一个版本, 2018 年 12 月 5 日发布了1.x 版本&#…

关于工作虚拟组的一些思考

这是学习笔记的第 2493篇文章 因为各种工作协作,势必要打破组织边界,可能会存在各种形态的虚拟组。 近期沉淀了一些虚拟组的管理方式,在一定时间范围内也有了一些起色,所以在不断沉淀的过程中,也在不断思考。 这三个虚…

Yocto - build/conf/local.conf文件

该文件是本地配置文件,所有本地用户设置都放置在此文件中。该文件中的注释为系统新用户可能需要更改的选项提供了一些指导,但几乎所有配置选项都可以在该文件中设置。更有冒险精神的用户可以查看 local.conf.sample.extended,其中包含了可以放…

Codeforces Round 975 (Div. 2) C. Cards Partition

题目链接:题目 大意: 给出若干种卡片,每种卡片有一定数量,你可以加入不超过 k k k张任意已给出种类的卡片,使得它们可以被分成若干组,每组容量一定,且同组内不存在相同种类的卡片,…