學習總結-《父與子的編程之旅》chapter 22


在本章,我們將了解如何打開文件以及如何讀寫文件(從文件獲取信息和在文件中存儲信息)。
動手試一試:
1.

import sys,random

adj = open('adj.txt','w')
adj.write("crazed\tsilly\tshy")
adj.close()

noun = open('none.txt','w')
noun.write('monkey\telephant\tcyclist')
noun.close()

verb = open('verb.txt','w')
verb.write('play\tdance\tflap')
verb.close()

adj_1 = open('adj.txt','r')
adj_text = adj_1.readline()
adj_new=adj_text.split('\t')
adj_1.close()

none_1 = open('none.txt','r')
noun_text = none_1.readline()
noun_new = noun_text.split('\t')
none_1.close()

verb_1 = open('verb.txt','r')
verb_text = verb_1.readline()
verb_new = verb_text.split('\t')
verb_1.close()

n = random.randint(0,2)

print('The'+' '+str(adj_new[n])+' '+str(noun_new[n])+' '+str(verb_new[n])+' .')

2、3:

import pickle
name = input('name')
age = input('age')
favorite = input('favorite')

my_file = open('myfile.txt','w')
my_file.write(name+"\n"+age+'\n'+favorite+'\n')
my_file.close()

pickle_file = open('pickle_file.pkl','wb')#用wb方式打開,不能用w方式打開
my_list = [name,age,favorite]
pickle.dump(my_list,pickle_file)
pickle_file.close()

pickle_file_r = open('pickle_file.pkl','rb') #同樣需要改成rb方式,pickle是二進制的
read_list = pickle.load(pickle_file_r)
pickle_file_r.close()

print(read_list)




注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com