我需要將嵌套串列以精確的 python 格式存盤在 csv 檔案中,即 [[1,2,3],[4,5,6],[7,8,9]]。
我想堅持使用 csv 模塊,所以我寫了下面的簡單代碼:
import csv
matrix = [[1,2,3],[4,5,6],[7,8,9]]
with open ('matrix.txt','w',newline='') as f:
content=csv.writer(f)
content.writerow(matrix)
上面的代碼在檔案中存盤了以下內容: "[1, 2, 4]","[2, 3, 5]","[3, 4, 6]" 所以,我們錯過了第一個和最后一個方括號和在頂部獲得多余的參考。
如檔案中所示,我嘗試了使用分隔符、引號字符和參考選項的各種選項,但沒有成功。如果轉換為字串,它會在每個字符之間插入一個逗號。
如何以原始格式(即[[1,2,3],[4,5,6],[7,8,9]])存盤精確的矩陣?
uj5u.com熱心網友回復:
如果您只想將串列存盤在檔案中而不完全依賴 csv 模塊,那么最簡單的方法之一是使用 python 提供的簡單檔案讀取器和寫入器。
看看這是否有幫助:
>>> import ast
>>>
>>> # Step 1: Storage
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> # Storing matrix as string
>>> with open("test.txt","w ") as fp:
... fp.write(str(matrix))
...
33
>>> # Reading the file
>>> with open("test.txt","r") as fp:
... res=fp.read()
... print(res)
... print(type(res))
...
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'str'>
>>> # Converting string back to list
>>> with open("test.txt","r") as fp:
... f=fp.read()
... res=ast.literal_eval(f)
... print(type(res))
... print(res)
...
<class 'list'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/523227.html
