python讀取TXT檔案資料並轉換為對應的矩陣

2021-10-09 11:05:44 字數 631 閱讀 4198

**:

from numpy import *

a = zeros((4, 4), dtype=float) # 先建立乙個全零方陣a,並且資料的型別設定為float浮點型

f = open('d:\\b.txt') # 開啟資料檔案檔案

lines = f.readlines() # 把全部資料檔案讀到乙個列表lines中

a_row = 0 # 表示矩陣的行,從0行開始

for line in lines: # 把lines中的資料逐行讀取出來

list = line.strip('\n').split(' ') # 處理逐行資料:strip表示把頭尾的'\n'去掉,split表示以空格來分割行資料,然後把處理後的行資料返回到list列表中

a[a_row:] = list[0:4] # 把處理後的資料放到方陣a中。list[0:4]表示列表的0,1,2,3列資料放到矩陣a中的a_row行

a_row += 1 # 然後方陣a的下一行接著讀

print(a)

執行結果:

VC讀取TXT檔案資料(1)

一 運用cstdiofile readstring cstdiofile f your file name cstring str while f.readstring str 二 程式實現 假設你已有了名為ts.txt的檔案在你的工程目錄下 o file.getposition 記錄上次的結果 讀...

VC讀取TXT檔案資料(1)

一 運用cstdiofile readstring cstdiofile f your file name cstring str while f.readstring str 二 程式實現 假設你已有了名為ts.txt的檔案在你的工程目錄下 o file.getposition 記錄上次的結果 讀...

解析txt檔案資料

publicclassfileaccessextendsactivitycatch exception e 讀檔案在.data data 包名 files 下面 param filename return publicstring readfiledata string filename catch...