一、文件操做总结
模式'r'或者‘r+’或者‘rb+’指针初始位置在文件开头
模式'w'或者‘w+’或者‘wb+’指针初始位置在文件末尾
模式'a'或者‘a+’或者‘ab+’指针初始位置在文件末尾git
模式'w'或者‘w+’或者‘wb+’,新建立文件,会覆盖原文件,慎用
file.truncate(20),文件从0开始只保留20个字符,其他被清除,慎用
file.readlines(),比较占用资源,对于大文件,尽可能不用
file.flush(),强制刷新新写入内容至磁盘app
二、文件练习:函数
__author__ = 'admin' f = open('file1','r+',encoding='utf-8') print(f.write('Yello++++')) ''' import sys,time for i in range(10): sys.stdout.write('#') sys.stdout.flush() time.sleep(0.2) f = open('file1','ab+') f.seek(0) print(f.readline()) print(f.readline()) print('\n=====\n') f.write('hello binary'.encode()) print(f.readline()) print(f.tell()) print(f.readline()) print(f.tell()) f.seek(60) print(f.tell()) print(f.readline()) print() #print(f.write('\nhello ---====----')) count = 0 for line in f : if count ==9 : print(f.write('this is an insert message')) count +=1 continue print(f.readline()) count +=1 '''
三、购物车练习:
readme:商品列表写在文件goods_list中,以只读方式打开,读取第一行,使用eval()函数转变为列表;先以只读方式打开username_info文件,eval()读取字典方式记录的{‘username’:[[选购清单],余额]}信息,关闭文件;提示输入用户名,判断用户名是否在username_info中,若是在,直接读取shopping_l 和salary;若是不在,则提示输入salary,而后选购,而后字典添加{‘username’:[[选购清单],余额]},最后写入信息,覆盖原先的'username_info'文件this
__author__ = 'Administrator' username = input('Please input your username:') #f_n = open('usernamelist','r+',encoding='utf-8') f_n_info = open('username_info','r',encoding='utf-8') salary = 0 goods_f = open('goods_list','r',encoding='utf-8') goods_l = eval(goods_f.readline()) goods_f.close() shopping_l = [] for index, item in enumerate(goods_l,0): print(index,item) def print_shopping(): print('----shopping list----') for i in shopping_l : print(i) print('Your current balance is :',salary) f_dict[username] =[shopping_l,salary] f_new_info = open('username_info','w+',encoding='utf-8') f_new_info.write(str(f_dict)) f_new_info.close() exit() f_dict = eval(f_n_info.readline()) f_n_info.close() if username in f_dict.keys() : shopping_l =f_dict[username][0] salary = f_dict[username][1] print(shopping_l,'\n',salary) else: salary = input('Please input your salary:') if salary.isdigit() : salary = int(salary) while True : choice = input('Please input the goods number (%s-%s):'%(0,len(goods_l))) if choice.isdigit() : choice = int(choice) if choice < len(goods_l) and choice >= -1 : p_item = goods_l[choice] if p_item[1] <= salary : shopping_l.append(p_item[0]) salary -= p_item[1] print('Add %s into your shopping cart,your current balance is:\033[31;1m %s\033[0m '%(p_item[0],salary)) else : print('You have no enough money.') print_shopping() else : print('Invalid number,please input again.') elif choice == 'q'or choice == 'Q' : print_shopping() # print('----shopping list----') # for i in shopping_l : # print(i) # print('Your current balance is :',salary) # exit() else: print('Invalid input,please input a number.') else: print('Invalid input') #for i in goods_l : # print(goods_l.index(i),i)