python可以处理的文件类型_Python学习笔记之数据类型与文件处理

1 #!/usr/bin/python3

2 #coding:utf-8

3 from __future__ importprint_function4 importos5 importrandom6 importsys7 '''

8 需求功能点9 -------------------------------------------------------10 购物:11 1.用户输入工资、然后打印购物菜单12 2.用户可以不断的购买商品、知道钱不够为止13 3.退出时格式化打印用户已购买的商品和剩余金额14 -------------------------------------------------------15 '''

16

17 __author__ = 'luting'

18

19

20 classShop(object):21

22 def __init__(self):23 self.test_data = {'user': 'luting', 'password': '123456', 'current_balance': '20000'}24

25 @staticmethod26 defread_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 incontext:39 value_list.append((value.decode('utf-8')).strip())40 returnvalue_list41 else:42 print('\033[1;31;0m The file is empty!\033[0m')43 return[]44 exceptFileNotFoundError as error:45 print('\033[1;31;0mThe FileNotFoundError is: {0}\033[0m'.format(error))46

47 @staticmethod48 defwrite_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) isFalse:57 print('\033[1;31;0mFile name is Error\033[0m')58 else:59 with open(file_path, 'a') as file:60 file.write(write_values + '\n')61

62 @staticmethod63 defidentifying_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 returncode75

76 deflogin_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 \033[31;1m%s\033[0m*******************************************************' %code)84 login_count =085 while login_count < 3:86 globalset_user87 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 inlock_user:91 input('\033[1;31;0mThe user has been locked!\033[0m')92 elif set_user == '' or set_password == '' or set_code == '':93 print('\033[1;31;0mThe input is empty!\033[0m')94 elif set_user not in self.test_data['user']:95 print('\033[1;31;0mUser name input error!\033[0m')96 elif set_user == self.test_data['user'] and set_password == self.test_data['password'] and set_code ==code:97 print('\033[31;1m*******************************************************%s,Welcome to the electronic mall!*******************************************************\033[0m' %set_user)98 print('\033[31m会员:%-20s当前余额:%s\033[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 \033[31;1m%s \033[0m chance' % (set_code, 2 -login_count))103 login_count += 1

104 else:105 self.write_txt('lock.txt', set_user)106

107 defshopping(self):108 """

109 购物 逻辑110 :return: 无返回值111 """

112 buy_shop_list =[]113 print('\033[31m\n商品列表:\033[0m')114 whileTrue:115 goods = self.read_text('goods.txt')116 if notgoods:117 print('There is no goods')118 else:119 goods_dict ={}120 goods_list =[]121 for goods_value ingoods:122 goods_list.append((str(goods_value).strip('\n')).split('.'))123 for good_value ingoods_list:124 goods_dict[good_value[0]] = good_value[1]125 print('\033[31m*******************************************************\n编号:%-5s 商品名称:%-15s 商品价格:(元)\033[0m' % ('\t', '\t'))126 for key, value ingoods_dict.items():127 index, goods_name, goods_price = key, (str(value).split(',')[0]), (str(value).split(',')[1])128 print('\033[31m%-10s\t %-20s \t %s\033[0m' %(index, goods_name, goods_price))129 print('\033[31m*******************************************************\033[0m')130 break

131 now_monkey = int(self.test_data['current_balance'])132 whileTrue:133 buy_input = str(input('Enter the number to buy the goods')).strip()134 if buy_input == '':135 print('\033[31mThe input is empty,please again!\033[0m')136 elif buy_input not in [key for key ingoods_dict.keys()]:137 print('\033[31mInput error, please again!\033[0m')138 else:139 price ={}140 for key, value ingoods_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 whileTrue:151 quit_input = str(input('Do you want to log out Y or N')).strip()152 if quit_input == '':153 print('\033[31mThe input is empty,please again!\033[0m')154 elif quit_input not in ['Y', 'N']:155 print('\033[31mInput error, please again!\033[0m')156 elif quit_input == 'Y':157 print(158 '\033[31m购买的商品:\n*******************************************************\n商品名称:%-15s 商品价格:(元)\033[0m' % '\t')159 if len(buy_shop_list) ==0:160 break

161 else:162 shop_list =[]163 for value inbuy_shop_list:164 shop_list.append(str(value).split(','))165 for shop_value inshop_list:166 print('\033[31m%-20s \t %s\033[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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值