Python 檔案IO的四種讀寫操作

2021-09-10 06:54:01 字數 1505 閱讀 9221

1. str()轉字串儲存;eval()轉資料型別讀取

d = }

with open('./test.txt', 'w') as file:

file.write(str(d)) # 轉字串儲存

with open('./test.txt', 'r') as file:

f = file.read()

f = eval(f) # 轉資料型別讀取

print(f,type(f))

2. json.dump()儲存到檔案;json.load()讀取資料

import json

d = }

with open('./json.txt', 'w') as file:

json.dump(d,file) # 將物件儲存到檔案

with open('./json.txt', 'r') as file:

f = json.load(file) # 按資料原型別讀取資料

print(f, type(f))

3. shelve 模組

import shelve

file = shelve.open('./test')

# 將多條資料寫入檔案

file['admin'] =

file['user'] =

# 從檔案中讀取多條資料

user = file['admin']

users = file['user']

# 列印結果

print(user,type(user))

print(users,type(users))

4. marshal 模組

import marshal

s = '漢族'

i = 99

f = 3.14159

b = true

c = 11 + 3j

l = [1,2,3]

d =

x = [s,i,f,b,c,l,d]

with open('./marshal.dat', 'wb') as file:

marshal.dump(len(x),file) # 儲存列表x的長度

for x1 in x:

marshal.dump(x1,file) # 儲存列表中多條資料內容

with open('./marshal.dat', 'rb') as file:

n = marshal.load(file) # 讀取檔案中資料長度

for x in range(n):

print(marshal.load(file)) # 遍歷,通過迴圈輸出檔案中的多條資料

colab讀寫外部檔案的四種方式

眾所周知,colab是google提供的執行在雲端的jupyter notebook環境。裡面整合了許多著名的機器學習python庫。由於這個環境是執行在google虛擬機器上的,顯然與自己的pc不在乙個檔案系統。那麼怎麼與我們自己的檔案互動呢?colab文件裡提供了四種方式,分別是 從本地直接上傳...

四種常用IO模型

1 同步阻塞io blocking io 2 同步非阻塞io non blocking io 3 io多路復用 io multiplexing 4 非同步io asynchronous io 注意以下概念 1.同步 非同步 同步和非同步是相對的 同步 前後兩件任務,有嚴格的順序一致性 依賴和遞進 按...

Python檔案讀寫IO操作

python中的檔案讀寫操作 我想大部分的程式語言的檔案讀寫操作都不會有太大差別基本上都是按照以下的步驟執行的 open開啟檔案 read,write讀或寫檔案 close關閉檔案 應牢記使用close關閉檔案python中一般使用以下方式進行檔案的讀寫 open file try read,wri...