zoukankan      html  css  js  c++  java
  • Python学习笔记之数据类型与文件处理

    Python文件处理

    #文件处理
    》》code
    
    f = file('myfile.txt','r')
    for line in f.readlines():
        line = line.strip('
    ').split(':')
        print(line)
    
    
    with open(file_name, 'r') as file
    #文件处理模式
    
    r 以只读的模式打开文件
    w 以只写模式打开文件
    a 以追加模式打开文件
    r+b 以读写模式打开   b二进制的形式处理文件
    w+b 以写读模式打开 
    a+b 以追加及读模式打开
    
    
    以w模式打开的时候如果文件中存在内容,则会把文件覆盖掉
    如果文件不存在,则会创建该文件
    
    不写处理模式,则默认为R的模式
    
    flush()刷新
    
    close()  关闭文件,返回布尔值
    
    seek()  跳到文件的任何位置 ,主要的功能跳到文件的开头
    
    tell()  反映当前所处的文件位置
    
    truncate() 清除文件内容
    
    writelines() 写多行
    
    xreadlines() 逐行读

     Pytho字符串处理

    s.find()指定范围查找
    s.rfind()反向查找
    s.index()同find 只是找不到产生valueerror异常
    s.rindex()同上反向查找
    s.count()返回找到子串个数
    
    lowsercase 
    capitalize 首字母大写
    lower 转小写
    upper 转大写
    swapcase  大小写互换
    
    split() 将string转list,以空格切分
    s.join()将list转string,以空格连接
    
    len() 串长度
    cmp() 字符串比较。第一个大,返回!
    max() 寻找字符串中最大的字符
    min() 寻找字符串中最小的字符
    startwith 以什么开头,返回布尔值
    endwithh 以什么结尾,返回布尔值
    replace()把 将字符串中的 str1 替换成 str2,

    Python列表

    [start, end, 步长] 根据索引取值
    append添加
    insert(位置,值)
    remove移除
    count计数
    index元素所处索引

    Python元祖

    type()类型
    isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
      

    isinstance() 与 type() 区别:

      type() 不会认为子类是一种父类类型,不考虑继承关系。

      isinstance() 会认为子类是一种父类类型,考虑继承关系。

      如果要判断两个类型是否相同推荐使用 isinstance()

      isinstance(object, classinfo)

        object -- 实例对象

        classinfo -- 可以是直接或间接类名、基本类型或者有它们组成的元组

    
    

    如果要判断两个类型是否相同推荐使用 isinstance()。

    
    list()
    tuple()
    元祖不可修改

    Python字典

    items()转换为list遍历key,value
    
    get(key)函数返回指定键的值,如果值不在字典中返回默认值。
    
    has_key()有该键返回true,否则false
    
    iteritems变成生成器
    
    keys()只显示字典的key
    values()只显示字典的values
    
    popitem随机删掉一个,字典是无序的。。。
    
    setdefault 如果键不已经存在于字典中,将会添加键并将值设为默认值
    
    update 新的字典更新老的字典。。。
    
    copy()拷贝。。。浅拷贝
    
    深copy
    import copy
    copy.deepcopy()
    
    
    直接赋值:其实就是对象的引用(别名)。
    浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
    深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。
    
    字典:
    插入,查找速度快。不会随着key增加而增加
    需要占用大量的内存,内存浪费多
    key不可变
    默认无序
    
    列表
    查找和插入的时间随着元素的增加而增加
    占用空间小,浪费内存小
    通过下标查询
    有序
    
    
    set集合
    特点:
       无序
       元素不重复
    功能:
       关系测试
       去重
    
    &交集
    | 并集
    - 差集
    ^ 反差集

    练习

     1 #!/usr/bin/python3
     2 # coding:utf-8
     3 import os
     4 import shutil
     5 import sys
     6 
     7 __author__ = 'luting'
     8 
     9 while True:
    10     input_order = str(input("input 'Y' Copy all | input 'N'  Copy one")).strip()
    11     if input_order == '':
    12         print('33[1;31;0m Order is empty,Please input again!33[0m')
    13     elif input_order not in ['Y', 'N']:
    14         print('33[1;31;0m Order is Error,Please input again!33[0m')
    15     elif input_order == 'Y':
    16         now_file = os.listdir(os.getcwd())
    17         if len(now_file) == 0:
    18             print('33[1;31;0m File is empty!33[0m')
    19         else:
    20             make_folder = input("DO you want to mkdir 'Y' or 'N'!")
    21             if make_folder == 'Y':
    22                 make_name = input('Please give name!')
    23                 copy_folder = os.path.join(os.getcwd(), make_name)
    24                 os.mkdir(copy_folder)
    25                 move_order = input("Do you want to move file to the new folder? 'Y' or 'N'")
    26                 for value in now_file:
    27                     copy_value = value[:value.find('.')] + '- 副本' + value[value.find('.'):]
    28                     shutil.copyfile(value, copy_value)
    29                     if move_order == 'Y':
    30                         shutil.move(copy_value, os.path.join(os.getcwd(), make_name))
    31                 while True:
    32                     remove_order = str(input("Do you want to Delete copy folder 'Y' or 'N'")).strip()
    33                     if remove_order == '':
    34                         print('33[1;31;0m Order is empty,Please input again!33[0m')
    35                     elif remove_order == 'Y':
    36                         shutil.rmtree(copy_folder)
    37                         break
    38                     else:
    39                         break
    40                 while True:
    41                     continue_order = str(input("Do you want to continue 'Y' or 'N'")).strip()
    42                     if continue_order == '':
    43                         print('33[1;31;0m Order is empty,Please input again!33[0m')
    44                         continue
    45                     elif continue_order == 'Y':
    46                         break
    47                     else:
    48                         sys.exit()
    49     else:
    50         file_name = str(input('Please input file name:')).strip()
    51         if file_name == '':
    52             print('33[1;31;0mFile name is empty, Please input again!33[0m')
    53         elif os.path.isfile(file_name) is False and os.path.exists(file_name) is False:
    54             print('33[1;31;0mFile name is Error, Please again33[0m')
    55         else:
    56             copy_file_name = file_name[:file_name.find('.')] + '- 副本' + file_name[file_name.find('.'):]
    57             print('33[1;32;0mThe file name is:33[0m	33[1;31;0m{0}33[0m'.format(copy_file_name))
    58             try:
    59                 with open(file_name, 'r') as file:
    60                     context = file.read()
    61                     while len(context) > 0:
    62                         with open(copy_file_name, 'w') as copy_file:
    63                             copy_file.write(context)
    64                             context = file.read()
    65             except PermissionError as error:
    66                 print('The PermissionError is:	{0}'.format(error))
    67             while True:
    68                 remove_order = str(input("Do you want to Delete copy file 'Y' or 'N'")).strip()
    69                 if remove_order == '':
    70                     print('33[1;31;0m Order is empty,Please input again!33[0m')
    71                 elif remove_order == 'Y':
    72                     os.remove(copy_file_name)
    73                     break
    74                 else:
    75                     break
    76             while True:
    77                 continue_order = str(input("Do you want to continue 'Y' or 'N'")).strip()
    78                 if continue_order == '':
    79                     print('33[1;31;0m Order is empty,Please input again!33[0m')
    80                     continue
    81                 elif continue_order == 'Y':
    82                     break
    83                 else:
    84                     sys.exit()
     1 #!/usr/bin/python3
     2 # coding:utf-8
     3 from __future__ import print_function
     4 import os
     5 import sys
     6 
     7 '''
     8 需求功能点:
     9     1.用户可以模糊查询员工信息
    10     2.显示匹配了多少条,匹配字符需要高亮显示
    11 '''
    12 
    13 __author__ = 'luting'
    14 
    15 while True:
    16     print('33[31;1m*******************************************************Welcome to the manual query system!*******************************************************33[0m')
    17     search_name = str(input('Please enter keywords to search')).strip()
    18     if search_name == '':
    19         print('33[31;1mThe input is empty33[0m')
    20     else:
    21         file_path = os.path.join(os.getcwd(), 'data.txt')
    22         file = open(file_path, 'r', encoding='utf-8')
    23         count = 0
    24         for line in file.readlines():
    25             if search_name in line:
    26                 print(line.replace(search_name, '33[31;1m%s33[0m' % search_name))
    27                 count += 1
    28         print('33[31;1m*******************************************************共找到%s条*******************************************************33[0m' % count)
    29         while True:
    30             continue_order = str(input('Do you want to continue  Y or N')).strip()
    31             if continue_order == '':
    32                 print('33[31;1mThe input is empty33[0m')
    33             elif continue_order not in ['Y', 'N']:
    34                 print('33[31;1mInput error33[0m')
    35             elif continue_order == 'Y':
    36                 break
    37             else:
    38                 sys.exit()
      1 #!/usr/bin/python3
      2 # coding:utf-8
      3 from __future__ import print_function
      4 import os
      5 import random
      6 import sys
      7 '''
      8 需求功能点
      9 -------------------------------------------------------
     10     购物:
     11         1.用户输入工资、然后打印购物菜单
     12         2.用户可以不断的购买商品、知道钱不够为止
     13         3.退出时格式化打印用户已购买的商品和剩余金额
     14 -------------------------------------------------------
     15 '''
     16 
     17 __author__ = 'luting'
     18 
     19 
     20 class Shop(object):
     21 
     22     def __init__(self):
     23         self.test_data = {'user': 'luting', 'password': '123456', 'current_balance': '20000'}
     24 
     25     @staticmethod
     26     def read_text(file_name):
     27         """
     28         读取 文本
     29         :param file_name: 文件名 string类型
     30         :return: 返回文本值,list类型
     31         """
     32         file_path = os.path.join(os.getcwd(), file_name)
     33         try:
     34             with open(file_path, 'rb') as file:
     35                 context = file.readlines()
     36                 if len(context) != 0:
     37                     value_list = []
     38                     for value in context:
     39                         value_list.append((value.decode('utf-8')).strip())
     40                     return value_list
     41                 else:
     42                     print('33[1;31;0m The file is empty!33[0m')
     43                     return []
     44         except FileNotFoundError as error:
     45             print('33[1;31;0mThe FileNotFoundError is: {0}33[0m'.format(error))
     46 
     47     @staticmethod
     48     def write_txt(file_name, write_values):
     49         """
     50         写入 文本
     51         :param file_name: 文件名 string类型
     52         :param write_values: 写入的文本值,string类型
     53         :return: 无返回值
     54         """
     55         file_path = os.path.join(os.getcwd(), file_name)
     56         if os.path.exists(file_path) is False and os.path.isfile(file_path) is False:
     57             print('33[1;31;0mFile name is Error33[0m')
     58         else:
     59             with open(file_path, 'a') as file:
     60                 file.write(write_values + '
    ')
     61 
     62     @staticmethod
     63     def identifying_code():
     64         """
     65         验证码
     66         :return: 四位验证码 string类型
     67         """
     68         code_num = random.randint(0, 9)
     69         letter = []
     70         for i in range(3):
     71             for letter_value in chr(random.randint(65, 90)):
     72                 letter.append(letter_value)
     73         code = str(code_num) + ''.join(letter)
     74         return code
     75 
     76     def login_main(self):
     77         """
     78         登录  逻辑
     79         :return:  无返回值
     80         """
     81         lock_user = self.read_text('lock.txt')
     82         code = self.identifying_code()
     83         print('*******************************************************verification code is 33[31;1m%s33[0m*******************************************************' % code)
     84         login_count = 0
     85         while login_count < 3:
     86             global set_user
     87             set_user = str(input('Please input user name!')).strip()
     88             set_password = str(input('Please input user password!')).strip()
     89             set_code = str(input('Please enter the verification code!')).strip()
     90             if set_user in lock_user:
     91                 input('33[1;31;0mThe user has been locked!33[0m')
     92             elif set_user == '' or set_password == '' or set_code == '':
     93                 print('33[1;31;0mThe input is empty!33[0m')
     94             elif set_user not in self.test_data['user']:
     95                 print('33[1;31;0mUser name input error!33[0m')
     96             elif set_user == self.test_data['user'] and set_password == self.test_data['password'] and set_code == code:
     97                 print('33[31;1m*******************************************************%s,Welcome to the electronic mall!*******************************************************33[0m' % set_user)
     98                 print('33[31m会员:%-20s当前余额:%s33[0m' % (self.test_data['user'],self.test_data['current_balance']))
     99                 self.shopping()
    100                 break
    101             else:
    102                 print('You input user name :%s is error,please input again!also 33[31;1m%s 33[0m chance' % (set_code, 2 - login_count))
    103             login_count += 1
    104         else:
    105             self.write_txt('lock.txt', set_user)
    106 
    107     def shopping(self):
    108         """
    109         购物  逻辑
    110         :return: 无返回值
    111         """
    112         buy_shop_list = []
    113         print('33[31m
    商品列表:33[0m')
    114         while True:
    115             goods = self.read_text('goods.txt')
    116             if not goods:
    117                 print('There is no goods')
    118             else:
    119                 goods_dict = {}
    120                 goods_list = []
    121                 for goods_value in goods:
    122                     goods_list.append((str(goods_value).strip('
    ')).split('.'))
    123                     for good_value in goods_list:
    124                         goods_dict[good_value[0]] = good_value[1]
    125                 print('33[31m*******************************************************
    编号:%-5s 商品名称:%-15s  商品价格:(元)33[0m' % ('	', '	'))
    126                 for key, value in goods_dict.items():
    127                     index, goods_name, goods_price = key, (str(value).split(',')[0]), (str(value).split(',')[1])
    128                     print('33[31m%-10s	 %-20s 	 %s33[0m' % (index, goods_name, goods_price))
    129                 print('33[31m*******************************************************33[0m')
    130                 break
    131         now_monkey = int(self.test_data['current_balance'])
    132         while True:
    133             buy_input = str(input('Enter the number to buy the goods')).strip()
    134             if buy_input == '':
    135                 print('33[31mThe input is empty,please again!33[0m')
    136             elif buy_input not in [key for key in goods_dict.keys()]:
    137                 print('33[31mInput error, please again!33[0m')
    138             else:
    139                 price = {}
    140                 for key, value in goods_dict.items():
    141                     price[key] = str(value).split(',')[1]
    142                 buy_price = price[buy_input]
    143                 buy_shop = goods_dict[buy_input]
    144                 if int(now_monkey) >= int(buy_price):
    145                     now_monkey -= int(buy_price)
    146                     buy_shop_list.append(buy_shop)
    147                     print('purchase succeeded! you have %s ¥' % now_monkey)
    148                 else:
    149                     print('You poor force,get out!')
    150                     while True:
    151                         quit_input = str(input('Do you want to log out Y or N')).strip()
    152                         if quit_input == '':
    153                             print('33[31mThe input is empty,please again!33[0m')
    154                         elif quit_input not in ['Y', 'N']:
    155                             print('33[31mInput error, please again!33[0m')
    156                         elif quit_input == 'Y':
    157                             print(
    158                                 '33[31m购买的商品:
    *******************************************************
    商品名称:%-15s  商品价格:(元)33[0m' % '	')
    159                             if len(buy_shop_list) == 0:
    160                                 break
    161                             else:
    162                                 shop_list = []
    163                                 for value in buy_shop_list:
    164                                     shop_list.append(str(value).split(','))
    165                                 for shop_value in shop_list:
    166                                     print('33[31m%-20s 	 %s33[0m' % (shop_value[0], shop_value[1]))
    167                                 sys.exit()
    168                         else:
    169                             break
    170 
    171 if __name__ == '__main__':
    172     shop = Shop()
    173     shop.login_main()
     1 #!/usr/bin/env python3
     2 # coding:utf-8
     3 from __future__ import print_function
     4 
     5 menu = {
     6     '数据与统计': {
     7       '数据分析': ['今日数据', '昨日走势'],
     8       '行为分析': ['心理分析', '外贸协会']
     9     },
    10     '资产管理': {
    11       '可用资产': ['用户当前资产', '流动形资产'],
    12       '当日盈亏': ['今日盈利', '今日亏损']
    13     },
    14     '用户设置': {
    15        '权限分配': ['菜单分配', '人员分配'],
    16        '人员新增': ['None', 'Null']
    17     },
    18 }
    19 
    20 
    21 while True:
    22     print('33[1;31;0m
    ************************************33[0m')
    23     for menu_key in [menu for menu in menu.keys()]:
    24         print('33[1;31;0m
    %s 33[0m' % menu_key)
    25     choose1 = str(input('请选择菜单')).strip()
    26     if choose1 == '':
    27         print('输入不可为空')
    28     elif choose1 not in [menu for menu in menu.keys()]:
    29         print('输入错误,请重新输入')
    30     else:
    31         if choose1 == [menu for menu in menu.keys()][0]:
    32             for menu_value in menu[[menu for menu in menu.keys()][0]].keys():
    33                 print('33[1;31;0m
    %s33[0m' % menu_value)
    34             choose_A = str(input('请选择菜单')).strip()
    35             if choose_A == '':
    36                 print('输入不可为空')
    37             elif choose_A not in [menu_value for menu_value in menu[[menu for menu in menu.keys()][0]].keys()]:
    38                 print('输入错误,请重新输入')
    39             else:
    40                 for value in menu[choose1][choose_A]:
    41                     print(value)
    42         elif choose1 == [menu for menu in menu.keys()][1]:
    43             for menu_value in menu[[menu for menu in menu.keys()][1]].keys():
    44                 print('33[1;31;0m
    %s33[0m' % menu_value)
    45             choose_B = str(input('请选择菜单')).strip()
    46             if choose_B == '':
    47                 print('输入不可为空')
    48             elif choose_B not in [menu_value for menu_value in menu[[menu for menu in menu.keys()][1]].keys()]:
    49                 print('输入错误,请重新输入')
    50             else:
    51                 for value in menu[choose1][choose_B]:
    52                     print(value)
    53         else:
    54             for menu_value in menu[[menu for menu in menu.keys()][2]].keys():
    55                 print('33[1;31;0m
    %s33[0m' % menu_value)
    56             choose_C = str(input('请选择菜单')).strip()
    57             if choose_C == '':
    58                 print('输入不可为空')
    59             elif choose_C not in [menu_value for menu_value in menu[[menu for menu in menu.keys()][2]].keys()]:
    60                 print('输入错误,请重新输入')
    61             else:
    62                 for value in menu[choose1][choose_C]:
    63                     print(value)
  • 相关阅读:
    0.嵌入式系统 Boot Loader 技术内幕
    JAVA_SE基础——25.面向对象练习
    JAVA_SE基础——24.面向对象的内存分析
    JAVA_SE基础——23.类的定义
    深入理解java的static关键字
    JAVA_SE基础——22.面向对象的概念
    JAVA_SE基础——21.二维数组的定义
    Java常用排序算法/程序员必须掌握的8大排序算法
    JAVA_SE基础——20.数组的常见操作
    JAVA_SE基础——19.数组的定义
  • 原文地址:https://www.cnblogs.com/xiaoxiaolulu/p/8057136.html
Copyright © 2011-2022 走看看