一、文件操做總結
模式'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)