zoukankan      html  css  js  c++  java
  • 08 练习题:文件操作

    # 1.有如下文件,a1.txt.txt,里面的内容为:
    # # 老男孩是最好的学校,
    # # 全心全意为学生服务,
    # # 只为学生未来,不为牟利。
    # # 我说的都是真的。哈哈
    
    # 分别完成以下的功能:
    # ​ a.将原文件全部读出来并打印。
    # ​ b,在原文件后面追加一行内容:信不信由你,反正我信了。
    # ​ c,将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了。
    # ​ d,将原文件全部清空,换成下面的内容:
    # # 每天坚持一点,
    # # 每天努力一点,
    # # 每天多思考一点,
    # # 慢慢你会发现,
    # # 你的进步越来越大。
    
    # ​ a.将原文件全部读出来并打印。
    with open(r'09 作业a1.txt.txt', encoding='utf-8', mode='r') as file_handler:
        for line in file_handler:
            line = line.strip('
    ')
            print(line)
    # ​ b,在原文件后面追加一行内容:信不信由你,反正我信了。
    with open(r'09 作业a1.txt.txt', encoding='utf-8', mode='a') as file_handler:
        file_handler.write('
    信不信由你,反正我信了。')
    # ​ c,将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了。
    with open(r'09 作业a1.txt.txt', encoding='utf-8', mode='r+') as file_handler:
        for line in file_handler:
            line = line.strip('
    ')
            print(line)
        file_handler.write('
    信不信由你,反正我信了。')
        file_handler.flush()
    # ​ d,将原文件全部清空,换成下面的内容:
    import os
    with open(r'09 作业a1.bak', encoding='utf-8', mode='w') as file_handler_1:
        file_handler_1.write('每天坚持一点,
    每天努力一点,
    每天多思考一点,
    慢慢你会发现,
    你的进步越来越大。')
    os.remove(r'09 作业a1.txt')
    os.rename(r'09 作业a1.bak', r'09 作业a1.txt')
    
    
    
    
    # 2.有如下文件,t1.txt,里面的内容为:
    # # 葫芦娃,葫芦娃,
    # # 一根藤上七个瓜
    # # 风吹雨打,都不怕,
    # # 啦啦啦啦。
    # # 我可以算命,而且算的特别准:
    # # 上面的内容你肯定是心里默唱出来的,对不对?哈哈
    
    # ​ 分别完成下面的功能:
    # ​ a,以r的模式打开原文件,利用for循环遍历文件句柄。
    # ​ b,以r的模式打开原文件,以readlines()方法读取出来,并循环遍历 readlines(),并分析b,与c 有什么区别?深入理解文件句柄与 readlines()结果的区别。
    # ​ c,以r模式读取‘葫芦娃,’前四个字符。
    # ​ d,以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符。
    # ​ e,以a+模式打开文件,先追加一行:‘老男孩教育’然后在从最开始将 原内容全部读取出来。
    
    # ​ a,以r的模式打开原文件,利用for循环遍历文件句柄。
    with open(r'09 作业	1.txt', encoding='utf-8', mode='r') as file_handler:
        for line in file_handler:
            line = line.strip('
    ')
            print(line)
    # ​ b,以r的模式打开原文件,以readlines()方法读取出来,并循环遍历 readlines(),并分析b,与a 有什么区别?深入理解文件句柄与 readlines()结果的区别。
    with open(r'09 作业	1.txt', encoding='utf-8', mode='r') as file_handler:
        for line in file_handler.readlines():
            line = line.strip('
    ')
            print(line)
    # ​ c,以r模式读取‘葫芦娃,’前四个字符。
    with open(r'09 作业	1.txt', encoding='utf-8', mode='r') as file_handler:
        print(file_handler.read(4))
    # ​ d,以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符。
    with open(r'09 作业	1.txt', encoding='utf-8', mode='r') as file_handler:
        line = file_handler.readline().strip()
        print(line)
    #   e,以a+模式打开文件,先追加一行:‘老男孩教育’然后再从最开始将原内容全部读取
    with open(r'09 作业	1.txt', encoding='utf-8', mode='a+') as file_handler:
        file_handler.write('
    老男孩教育')
        file_handler.seek(0)
        print(file_handler.read()[:-5])
    
    
    
    
    
    # 3.文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
    # # apple 10 3
    # # tesla 100000 1
    # # mac 3000 2
    # # lenovo 30000 3
    # # chicken 10 3
    
    # ​ 通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
    merchandise_list = []
    name_list = ['name', 'price', 'amount']
    with open(r'09 作业a.txt', encoding='utf-8', mode='r') as file_handler:
        for info in file_handler:
            temp_dic = {}
            line_list = info.strip().split(' ')
            for index in range(len(name_list)):
                if line_list[index].isdecimal():
                    line_list[index] = int(line_list[index])
                temp_dic[name_list[index]] = line_list[index]
            merchandise_list.append(temp_dic)
    print(merchandise_list)
    
    
    
    
    # 4.有如下文件:
    # # alex是老男孩python发起人,创建人。
    # # alex其实是人妖。
    # # 谁说alex是sb?
    # # 你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
    
    # 将文件中所有的alex都替换成大写的SB(文件的改的操作)。
    import os
    with open(r'09 作业alex自述', encoding='utf-8', mode='r') as file_handler_1,
            open(r'09 作业alex自述.bak', encoding='utf-8', mode='w') as file_handler_2:
        for line in file_handler_1:
            line = line.strip('
    ')
            new_line = line.replace('alex', 'SB')
            file_handler_2.write(new_line + '
    ')
    os.remove(r'09 作业alex自述')
    os.rename(r'09 作业alex自述.bak', r'09 作业alex自述')
    
    
    
    
    # 5.文件a1.txt内容(选做题)
    # # name:apple price:10 amount:3 year:2012
    # # name:tesla price:100000 amount:1 year:2013
    
    # ​ 通过代码,将其构建成这种数据类型:
    # ​ [{'name':'apple','price':10,'amount':3,year:2012},
    # ​ {'name':'tesla','price':1000000,'amount':1}......]
    # ​ 并计算出总价钱。
    merchandise_list=[]
    total_amount = 0
    with open(r'09 作业a1.txt', encoding='utf-8', mode='r') as file_handler:
        temp_list = file_handler.readlines()
        for line in temp_list:
            temp_dic = {}
            name, price, amount, year = line.strip().split(' ')
            temp_dic['name'] = name[5:]
            temp_dic['price'] = price[6:]
            temp_dic['amount'] = amount[7:]
            temp_dic['year'] = name[5:]
            total_amount += int(temp_dic['price'])
            merchandise_list.append(temp_dic)
    print(merchandise_list, total_amount)
    
    
    
    
    # 6.文件a1.txt内容(选做题)
    # # 序号 部门 人数 平均年龄 备注
    # # 1 python 30 26 单身狗
    # # 2 Linux 26 30 没对象
    # # 3 运营部 20 24 女生多
    # # .......
    
    # 通过代码,将其构建成这种数据类型:
    # [{'序号':'1','部门':Python,'人数':30,'平均年龄':26,'备注':'单身狗'},
    # ......]
    department_list = []
    with open(r'09 作业a1.txt', encoding='utf-8', mode='r') as file_handler:
        keys = file_handler.readline().strip().split(' ')
        for line in file_handler:
            temp_dic = {}
            # cnt = 0
            # for key in keys:
            #     temp_dic.setdefault(key, line.strip().split(' ')[cnt])
            #     cnt += 1
            for key in enumerate(keys):                                         # 用 numerate 枚举法省去了一个 cnt 变量的操作
                temp_dic.setdefault(key[1], line.strip().split(' ')[key[0]])
            department_list.append(temp_dic)
    print(department_list)
    
  • 相关阅读:
    day7 面向对象 静态方法 类方法 属性方法 类的特殊成员方法 元类 反射 异常处理
    day6 面向对象 封装 继承 多态 类与实例在内存中的关系 经典类和新式类
    day5 time datetime random os sys shutil json pickle shelve xml configparser hashlib subprocess logging re正则 python计算器
    kafka常用操作命令
    linux基础
    django学习1——初识web应用程序
    mysql数据库(三)——pymysql模块
    mysql数据库(二)——表的查询
    mysql数据库(一)
    Python常用模块——re模块
  • 原文地址:https://www.cnblogs.com/raygor/p/13255063.html
Copyright © 2011-2022 走看看