day3.04

本文介绍了如何在Python中通过文件操作实现数据持久化,包括文件的打开、读写、关闭,以及使用`open()`函数的不同模式和编码。通过实例演示了如何创建、更新和读取文件,以及使用文件记录程序执行次数和学生信息。
摘要由CSDN通过智能技术生成

day3.04-文件操作

1. 文件操作

1. 数据持久化

'''
1)背景:程序中数据默认保存在内存中,保存在运行内存中的数据在程序运行结束后会被销毁
    如果想要程序中的数据在程序借宿后不被销毁必须将数据通过文件形式保存在磁盘中
2)数据持久化又叫数据本地化,就是将程序中的数据储存在文件中
3)常见的数据持久化工具:数据库(.db,.sqlite)、json文件、plist文件、csv文件、excel文件、txt文件

'''

2. 文件操作

  • 2.1 打开文件

    '''
    文件操作基本流程:打开文件   ->  操作文件(读、写)   ->  关闭文件
    
    '''
    
    '''
    open(files,mode='r',*,encoding=None)
    1)files  -   需要打开的文件的路径(可以是绝对路径也可以是相对路径)
                注意:相对路径如果是'./'开头'./'可以省略
    2)mode  -   文件打开方式:由两组值决定打开文件后能干什么,同时决定操作文件的时候数据的类型
                第一组(决定能该干什么):r、w、a
                r   -   只读
                w   -   只写,会清空原文件内容,如果文件不存在会创建文件
                a   -   只写,不会清空原文件内容,如果文件不存在会创建文件
                +   -   读写:r+、a+、w+
                
                第二组(决定数据类型):t、b
                t   -   字符串
                b   -   字节(二进制数据)
                打开文本可以用t也可以用b,但是二进制文件只能用b打开
                使用时必须在每一组值中选一个,如果第二组值没选,相当于选的't',例如'rt','r','rb','br','wt','bw','ba','a'
    3)encoding  -   文件编码方式(文本文件文字存储的时候采用的字符集) 
                    只有在以t方式打开文件的时候才需要设置encoding
                    一般赋值为 
                    'utf-8'   ->  数字、字母使用1字节;中文采用3个字节;emoj表情采用4个字节
                    'gbk'   ->  中文采用4个字节
                
    '''
    # f = open('files/aaa.txt', 'r',encoding='utf-8')
    # # result = f.read()
    # # print(result)
    # print(f.read())
    
    # f = open('files/aaa.txt', 'w',encoding='utf-8')
    # f.write('aaj')
    # f.read()
    
    # f = open('files/aaa.txt', 'a',encoding='utf-8')
    # f.write('ajdajdka')
    #
    # f = open('files/aaa.txt', 'rb')
    # f.read()
    # f = open('files/aaa.txt', 'rb')
    # f.read()
    
  • 2.2 操作文件

'''
1)读操作:
文件对象.read() -   从读写位置开始读到文件结束(获取整个文件内容),返回值就是文件内容
文件对象.readline() -   从读写位置开始,读到一行结束,只能读文本数据

'''
# f = open('files/aaa.txt', 'r')
# result = f.read()
#
# print(f.read())

# f.seek(0)   # 将读写位置移动到文件开头

'''
2)写操作
文件对象.write(数据)  -   将指定数据写入指定文件
'''
  • 2.3 关闭文件
# 文件操作完后要关闭文件:文件对象.close()

# 防止忘记忘记关闭文件的方法1:
result = open('files/aaa.txt',encoding='utf-8').read()
print(result)
# 防止忘记忘记关闭文件的方法2:
with open('files/aaa.txt',encoding='utf-8') as f:
    result = f.read()
    print(result)

2. 数据持久化

数据持久


'''
第一步:确定需要持久化的数据
第二步:创建文件并且确定文件初始内容
第三步:这程序中需要这个数据的时候从文件中中读取这个数据
第四步:当这个数据改变以后需要将最新的数据写入文件中

'''



# 练习1:写程序打印程序执行次数
# import os
# path_now = os.getcwd()
# test1 = '运行次数.txt'
# path_new = os.path.join(path_now,test1)
# # print(path_new)
# try:
#     f = open(path_new,'a',encoding='utf-8')
# except:
#     f = open(path_new,'a')
# try:
#     f = open(path_new,'r',encoding='utf-8')
# except:
#     f = open(path_new,'r')
# value = f.read()
# if value == '':
#     result = 1
# else:
#     result = int(value) + 1
#
# try:
#     f = open(path_new,'w',encoding='utf-8')
# except:
#     f = open(path_new,'w')
# f.write(str(result))
# print(result)


# 练习2:写程序添加学生并且打印已经添加过的所有学生
# import os
# test2 = '学生名单.txt'
# path_new1 = os.path.join(path_now,test2)
# # print(path_new1)
# try:
#     f = open(path_new1,'a',encoding='utf-8')
# except:
#     f = open(path_new1,'a')
# name = input('请输入学生名字:')
# f.write(' ' + name)
# try:
#     f = open(path_new1,'r',encoding='utf-8')
# except:
#     f = open(path_new1,'r')
# result1 = f.read()
# print(result1)


# 练习3:写程序添加学生,并且打印已经添加过的所有学生
"""
第1次运行程序:
    请输入学生姓名: 小明
    [小明]

第2次运行程序:
    请输入学生姓名: 小花
    [小明, 小花]

第3次运行程序:
    请输入学生姓名: 小红
    [小明, 小花, 小红]
....
"""
# import os
# path_now = os.getcwd()
# test3 = '学生列表.txt'
# path_stu = os.path.join(path_now,test3)
# # print(path_new)
# f =open(path_stu,'r',encoding='utf-8')
# stu_name = f.read()
# # print(stu_list1)
# stu_list = stu_name.split(',')
# # print(stu_list)
# name_stu = input('请输入学生名字:')
# for i in range(len(stu_list)):
#     if stu_list[i] == name_stu:
#         print(stu_list[:i+1])





# 练习4:写程序添加学生,并且打印已经添加过的所有学生
"""
请输入学生姓名: 小明
请输入学生电话: 110
请输入学生专业: 电子信息
[
    {'name': '小明', 'tel': '110', 'major': '电子信息'}
]


请输入学生姓名: 小花
请输入学生电话: 119
请输入学生专业: 服装设计
[
    {'name': '小明', 'tel': '110', 'major': '电子信息'},
    {'name': '小花', 'tel': '119', 'major': '服装设计'}
]
"""
import os
path_now = os.getcwd()
test4 = '学生信息.txt'
path_stu_infor = os.path.join(path_now,test4)
f =open(path_stu_infor,'r',encoding='utf-8')
stu_infor = f.read()
# print(stu_infor)
# result = stu_infor.split('{')
# print(result)


stu_dict = {}

作业

import os,sys
print('=' * 31)
print(' ' * 6,'欢迎来到学生管理系统','\n')
print(' ' * 8,'● 1. 登  陆')
print(' ' * 8,'● 2. 注  册')
print(' ' * 8,'● 3. 退  出')
print('=' * 31)
path_now = os.getcwd()
test1 = '账号目录.txt'
path_id = os.path.join(path_now,test1)
f = open(path_id,'a',encoding='utf-8')
f.close()
test2 = '账号密码.txt'
path_id_info = os.path.join(path_now,test2)
try:
    id_list = eval(open(path_id).read())
except FileExistsError:
    id_list = []
chioce1 = int(input('请选择(1~3):'))
while chioce1 == 2:
    id = input('请输入账号(3-6位):')
    while len(id) not in range(3,7):
        print('账号超出位数,请重新上输入。')
        print('● 1. 重新输入账号')
        print('● 2. 退出')
        chioce11 = int(input('请输入选择:'))
        if chioce11 == 1:
            id = input('请输入账号(3-6位):')
        else:
            sys.exit()
    else:
        while id in id_list:
            print('对不起该账号已注册,请重新输入账号名。')
            print('● 1. 重新输入账号')
            print('● 2. 退出')
            chioce11 = input('请输入选择:')
            if chioce11 == 1:
                id = input('请输入账号(3-6位):')
            else:
                sys.exit()


        else:
            password = input('请输入你的密码:')
            id_list.append(id)

            f = open(path_id,'w')
            f.write(str(id_list))
            e = open(path_id_info,'a',encoding='utf-8')
            e.close()
            try:
                id_pw_list = eval(open(path_id_info).read())
            except:
                id_pw_list = []
            id_pw = (id,password)
            id_pw_list.append(id_pw)
            # print(id_pw_list)
            e = open(path_id_info,'w',encoding='utf-8').write(str(id_pw_list))
            print('恭喜你注册成功!')
            print('现在你可以使用账号密码登陆了!')
            break
while chioce1 == 1:
    id = input('请输入账号:')
    pw = input('请输入您的密码:')
    id_pw =  (id,pw)
    id_pw_list1 = eval(open(path_id_info,'r',encoding='utf-8').read())
    while id_pw not in id_pw_list1:
        print('账号密码错误!')
        print('● 1. 重新输入账号')
        print('● 2. 退出')
        chioce22 = int(input('请选择:'))
        if chioce22 == 1:
            id = input('请输入账号:')
            pw = input('请输入您的密码:')
        else:
            sys.exit()
    else:
        print('恭喜您登录成功!')
        print('=' * 31)
        print(' ' * 6, '欢迎',id,':' ,'\n')
        print(' ' * 8, '● 1. 添加学生')
        print(' ' * 8, '● 2. 查看学生')
        print(' ' * 8, '● 3. 修改学生信息')
        print(' ' * 8, '● 4. 删除学生')
        print(' ' * 8, '● 5. 退出')
        print('=' * 31)
        chioce23 = int(input('请输入选择:'))
        test3 = id + '_stu.txt'
        path_stu = os.path.join(path_now,test3)
        f = open(path_stu, 'a', encoding='utf-8')
        f.close()
        # =======================
        while chioce23 == 1:
            try:
                stu_info = eval(open(path_stu,'r').read())
            except:
                stu_info = []

            stu_name = input('请输入学生名字:')
            stu_age = input('请输入学生年龄:')
            stu_tel = input('请输入学生电话:')
            stu_num = 'stu' + input('请输入学生学号:')
            stu_info_dict = {
                'name':stu_name,
                'age':stu_age,
                'tel':stu_tel,
                'num':stu_num
            }
            stu_info.append(stu_info_dict)

            f = open(path_stu,'w').write(str(stu_info))

            print('添加成功!')
            print('1. 继续')
            print('2. 返回')
            chioce232 = int(input('请输入选择:'))
            if chioce232 == 1:
                continue
            else:
                print('=' * 31)
                print(' ' * 6, '欢迎', id, ':', '\n')
                print(' ' * 8, '● 1. 添加学生')
                print(' ' * 8, '● 2. 查看学生')
                print(' ' * 8, '● 3. 修改学生信息')
                print(' ' * 8, '● 4. 删除学生')
                print(' ' * 8, '● 5. 退出')
                print('=' * 31)
                chioce23 = int(input('请输入选择:'))
        # =======================
        while chioce23 == 2:
            try:
                f = eval(open(path_stu).read())
            except:
                f = []
            print('1. 查看所有学生')
            print('2. 按姓名查找')
            print('3. 按学号查找')
            print('其他返回')
            chioce231 = int(input('请输入选择:'))
            if chioce231 == 1:
                for i in f:
                    print(i)
            elif chioce231 == 2:
                name_find = input('请输入名字:')
                for i in f:
                    if i['name'] == name_find:
                        print(i)
            elif chioce231 == 3:
                num_find = input('请输入学号:')
                for i in f:
                    if i['num'] == num_find:
                        print(i)
                        break
            else:
                print('=' * 31)
                print(' ' * 6, '欢迎', id, ':', '\n')
                print(' ' * 8, '● 1. 添加学生')
                print(' ' * 8, '● 2. 查看学生')
                print(' ' * 8, '● 3. 修改学生信息')
                print(' ' * 8, '● 4. 删除学生')
                print(' ' * 8, '● 5. 退出')
                print('=' * 31)
                chioce23 = int(input('请输入选择:'))
        while chioce23 == 3:
            try:
                f = eval(open(path_stu).read())
            except:
                f = []
            num_change = input('请输入要修改的学生学号:')
            for i in f:
                if i['num'] == num_change:
                    stu_info_change = i
                    print(stu_info_change)
                    print('请选择要修改的信息')
                    print('1. name')
                    print('2. age')
                    print('3. tel')
                    chioce233 = int(input('请输入选择:'))
                    if chioce233 == 1:
                        name_new = input('请输入新名字:')
                        i['name']=name_new
                    elif chioce233 == 2:
                        age_new = input('请输入新年龄:')
                        i['age'] = age_new
                    else:
                        tel_new = input('请输入新电话:')
                        i['tel'] = tel_new
                    f1 = open(path_stu,'w')
                    f1.write(str(f))
                    print('修改完成!')
                    print('1. 继续')
                    print('2. 退出')
                    chioce234 = input('请输入选择:')
                    if chioce234 == 1:
                        continue
                    else:
                        print('=' * 31)
                        print(' ' * 6, '欢迎', id, ':', '\n')
                        print(' ' * 8, '● 1. 添加学生')
                        print(' ' * 8, '● 2. 查看学生')
                        print(' ' * 8, '● 3. 修改学生信息')
                        print(' ' * 8, '● 4. 删除学生')
                        print(' ' * 8, '● 5. 退出')
                        print('=' * 31)
                        chioce23 = int(input('请输入选择:'))


            else:
                print('您没有这个学生。')
                print('1. 继续')
                print('2. 退出')
                chioce235 = int(input('请输入选择:'))
                if chioce235 == 1:
                    continue
                else:
                    print('=' * 31)
                    print(' ' * 6, '欢迎', id, ':', '\n')
                    print(' ' * 8, '● 1. 添加学生')
                    print(' ' * 8, '● 2. 查看学生')
                    print(' ' * 8, '● 3. 修改学生信息')
                    print(' ' * 8, '● 4. 删除学生')
                    print(' ' * 8, '● 5. 退出')
                    print('=' * 31)
                    chioce23 = int(input('请输入选择:'))
        while chioce23 == 4:
            print('请选择删除方式:')
            print('1. 学号')
            print('2. 名字')
            chioce42 = int(input('请选择:'))
            try:
                f_delet = eval(open(path_stu).read())
            except:
                print('您没有学生可删除!')
                print('1. 继续')
                print('2. 退出')
                chioce43 = int(input('请输入选择:'))
                if chioce43 == 1:
                    continue
                else:
                    print('=' * 31)
                    print(' ' * 6, '欢迎', id, ':', '\n')
                    print(' ' * 8, '● 1. 添加学生')
                    print(' ' * 8, '● 2. 查看学生')
                    print(' ' * 8, '● 3. 修改学生信息')
                    print(' ' * 8, '● 4. 删除学生')
                    print(' ' * 8, '● 5. 退出')
                    print('=' * 31)
                    chioce23 = int(input('请输入选择:'))
                    break

            if chioce42 == 1:
                num_del = input('请输入学号:')
                for i in f_delet:
                    while i['num'] == num_del:
                        f_delet.remove(i)
                        f11 = open(path_stu,'w').write(f_delet)
                        print('删除成功!')
                        print('1. 继续')
                        print('2. 退出')
                        chioce425 = int(input('请输入选择:'))
                        if chioce425 == 1:
                            continue
                        else:
                            print('=' * 31)
                            print(' ' * 6, '欢迎', id, ':', '\n')
                            print(' ' * 8, '● 1. 添加学生')
                            print(' ' * 8, '● 2. 查看学生')
                            print(' ' * 8, '● 3. 修改学生信息')
                            print(' ' * 8, '● 4. 删除学生')
                            print(' ' * 8, '● 5. 退出')
                            print('=' * 31)
                            chioce23 = int(input('请输入选择:'))
                        continue
                else:
                    print('没有该学生')
                    print('1. 继续')
                    print('2. 退出')
                    chioce44 = int(input('请输入选择:'))
                    if chioce44 == 1:
                        continue
                    else:
                        print('=' * 31)
                        print(' ' * 6, '欢迎', id, ':', '\n')
                        print(' ' * 8, '● 1. 添加学生')
                        print(' ' * 8, '● 2. 查看学生')
                        print(' ' * 8, '● 3. 修改学生信息')
                        print(' ' * 8, '● 4. 删除学生')
                        print(' ' * 8, '● 5. 退出')
                        print('=' * 31)
                        chioce23 = int(input('请输入选择:'))
                        break
            if chioce42 == 2:
                name_del = input('请输入删除学生名字:')
                name_del_list = []
                for j in f_delet:
                    if j['name'] == name_del:
                        name_del_list.append(j)
                if name_del_list == []:
                    print('没有该学生')
                    print('1. 继续')
                    print('2. 退出')
                    chioce45 = int(input('请输入选择:'))
                    if chioce45 == 1:
                        continue
                    else:
                        print('=' * 31)
                        print(' ' * 6, '欢迎', id, ':', '\n')
                        print(' ' * 8, '● 1. 添加学生')
                        print(' ' * 8, '● 2. 查看学生')
                        print(' ' * 8, '● 3. 修改学生信息')
                        print(' ' * 8, '● 4. 删除学生')
                        print(' ' * 8, '● 5. 退出')
                        print('=' * 31)
                        chioce23 = int(input('请输入选择:'))
                        break
                else:
                    for x in name_del_list:
                        print(name_del_list.index(x),x)

                    num1 = int(input('请选择要删除的学生:'))
                    if num1 in range(len(name_del_list)):
                        f_delet.remove(name_del_list[num1])
                        f12 = open(path_stu, 'w').write(f_delet)
                        print('删除成功!')
                        print('1. 继续')
                        print('2. 退出')
                        chioce426 = int(input('请输入选择:'))
                        if chioce426 == 1:
                            continue
                        else:
                            print('=' * 31)
                            print(' ' * 6, '欢迎', id, ':', '\n')
                            print(' ' * 8, '● 1. 添加学生')
                            print(' ' * 8, '● 2. 查看学生')
                            print(' ' * 8, '● 3. 修改学生信息')
                            print(' ' * 8, '● 4. 删除学生')
                            print(' ' * 8, '● 5. 退出')
                            print('=' * 31)
                            chioce23 = int(input('请输入选择:'))
            else:
                print('=' * 31)
                print(' ' * 6, '欢迎', id, ':', '\n')
                print(' ' * 8, '● 1. 添加学生')
                print(' ' * 8, '● 2. 查看学生')
                print(' ' * 8, '● 3. 修改学生信息')
                print(' ' * 8, '● 4. 删除学生')
                print(' ' * 8, '● 5. 退出')
                print('=' * 31)
                chioce23 = int(input('请输入选择:'))
        else:
            break
else:
    sys.exit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值