python中的文件操作处理:文本文件的处理、二进制文件的处理

发布于:2025-06-14 ⋅ 阅读:(20) ⋅ 点赞:(0)

不同文件类型

文本类型:普通字符文件,默认unicode字符集,记事本可打开

文本文件的复制

# 文本文件
source_path = r"C:\Users\maido\Desktop\测试python文件.txt"
destionPath = r"C:\Users\maido\Desktop\copy测试python文件.txt"

# 模式:rt-read text; wt-writetext
with open(source_path, mode="rt", encoding="utf-8") as reader:
    lines = reader.read()
    with open(destionPath, mode="wt", encoding="utf-8") as writer:
        writer.write(lines)

执行结果
在这里插入图片描述
且对应路径下出现已经复制好的文件
在这里插入图片描述

二进制文件:jpg、mp3、mp4等

python中最常用的文件管理的方式是通过with来管理上下文的资源关闭情况

非文本文件复制

非文本文件的复制和文本文件的复制最大的区别在于,非文本文件在复制时候是不能够指定文件编码的,例如像文本文件那样指定为utf-8,且复制的模式需要更改,rb - read binary、wb - writer binary。

# 文本文件
source_path = r"C:\Users\maido\Desktop\测试python非文本文件复制.png"
destionPath = r"C:\Users\maido\Desktop\copy测试python非文本文件复制.png"

# 模式:rb-read binary; wb-write binary,非文本文件路径不能指定utf-8这种编码
with open(source_path, mode="rb") as reader:
    lines = reader.read()
    with open(destionPath, mode="wb") as writer:
        writer.write(lines)

执行结果
在这里插入图片描述
且在对应路径下出现复制的文件
在这里插入图片描述

综合案例

# 登录日志相关
import time

FileName = 'log.txt'
def record_log(user, status):
    #先做写的操作,a - append模式,写入数据到日志,直接append,编码问题uft-8
    with open(FileName, 'a', encoding= 'utf-8') as f:
        log = f'登录用户:{user},{status},登录时间:{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}'
        f.write(log + '\n')


def read_log():
    with open(FileName, 'rt', encoding= 'utf-8') as f:
        for line in f.readlines():
            line = line.strip()
            print(line)

# 接收用户名、密码
user = input("请输入名称")
pwd = input("请输入密码")

# 展示界面
def show_menu():
    menu = '''
        ***********
        1.当前登录用户
        2.查看登录日志
        3.退出系统
    '''
    print(menu)

#mock数据库
if user in ('a','b','c') and pwd == "666":
    record_log(user, '登录成功')
    # 展示界面-保证界面不退出
    while True:
        show_menu()
        choice = input("请输入您的操作码")
        if choice == '1':
            print("当前用户:", user)
        elif choice == '2':
            read_log()
        elif choice == '3':
            record_log(user, "退出系统")
            print("感谢使用下次见")
            break
        else:
            print("请输入有效数字")
else:
    print('登录失败您的用户名或者密码有错误')
    record_log(user, '登录失败')

执行结果
在这里插入图片描述