重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
這篇文章主要講解了“python的文件操作和Pick存儲模塊實例”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“python的文件操作和Pick存儲模塊實例”吧!
創新互聯建站主要從事成都網站制作、做網站、外貿營銷網站建設、網頁設計、企業做網站、公司建網站等業務。立足成都服務巢湖,十多年網站建設經驗,價格優惠、服務專業,歡迎來電咨詢建站服務:028-86922220
文件操作
輸入:
#!/usr/bin/python
# Filename: using_file.py
poem = '''\Programming is funWhen the work is doneif you wanna make your work also fun: use Python!'''
f = open('poem.txt', 'w')
# open for 'w'riting
f.write(poem)
# write text to file
f.close()
# close the file
f = open('poem.txt')
# if no mode is specified, 'r'ead mode is assumedby default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print(line, end='')
f.close()
# close the file
輸出:
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
解釋:
本例中,設計到了文件的讀寫操作。
首先定義了一個字符串,打開一個文件,將數據存入,保存。
然后打開這個剛才保存的文件,按行輸出內容。
Pickle模塊
輸入:
#!/usr/bin/python
# Filename: pickling.py
import pickle
# the name of the file where we will store the objectshoplistfile = 'shoplist.data'
# the list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f)
# dump the object to a file
f.close()
del shoplist
# destroy the shoplist variable
# Read back from the storage
輸出:
$ python pickling.py
['apple', 'mango', 'carrot']
解釋:
Python提供了一個名為 pickle的標準模塊,您可以使用它存儲任何Python
文件中的對象,然后再將其取回。 這稱為持久存儲對象。
感謝各位的閱讀,以上就是“python的文件操作和Pick存儲模塊實例”的內容了,經過本文的學習后,相信大家對python的文件操作和Pick存儲模塊實例這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創新互聯,小編將為大家推送更多相關知識點的文章,歡迎關注!