溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python的文件操作和Pick存儲模塊實例

發(fā)布時間:2021-09-03 18:43:37 來源:億速云 閱讀:175 作者:chen 欄目:大數據

這篇文章主要講解了“python的文件操作和Pick存儲模塊實例”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“python的文件操作和Pick存儲模塊實例”吧!


文件操作

輸入:


#!/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存儲模塊實例這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI