與小卡特一起學python 第22章 檔案輸入與輸出

yarking207發表於2016-04-26
#22-1 開啟和讀檔案
my_file = open('notes.txt','r')
lines = my_file.readlines()
print(lines)
my_file.close()


#22-2 多次使用readline()
my_file = open('notes.txt','r')
first_line = my_file.readline()
second_line = my_file.readline()
print("first line = ",first_line)
print("second line = ",second_line)
my_file.close()


#22-21 seek()
my_file = open('notes.txt','r')
first_line = my_file.readline()
second_line = my_file.readline()
print("first line = ",first_line)
print("second line = ",second_line)
my_file.seek(5)
first_line_again = my_file.readline()
print(first_line_again)
my_file.close()


#22-3使用追加模式

todo_list = open("notes.txt","a")
todo_list.write ("\nSpeed allowance")
todo_list.close()

#22-4 對一個新檔案使用寫模式
new_file = open("my_new_notes.txt","w")
new_file.write("Eat supper\n")
new_file.write("Play soccer\n")
new_file.write("Go to bed")
new_file.close()

#22-5 對一個現有檔案使用寫模式
the_file = open("notes.txt","w")
the_file.write("Wake up\n")
the_file.write("Watch cartoons")
the_file.close()

my_file = open('notes.txt','r')
lines = my_file.readlines()
print(lines)
my_file.close()

#22-6 使用pickle將列表儲存到檔案中
import pickle
my_list = ['Fred',73,'Hello there',8.19876e-13]
pickle_file = open('my_pickled_list.pkl','wb')#wb二進位制儲存 與書中不一樣
pickle.dump(my_list,pickle_file,1)
pickle_file.close()


#22-7 使用load()還原
import pickle
pickle_file = open('my_pickled_list.pkl','rb')#二進位制開啟
recovered_list = pickle.load(pickle_file)
pickle_file.close()
print(recovered_list)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/220205/viewspace-2088972/,如需轉載,請註明出處,否則將追究法律責任。

相關文章