Python讀取文字檔案到陣列

2021-10-14 13:02:26 字數 972 閱讀 2257

支援的格式有txt, dat, csv, mat等

讀入的資料存為float型別, 可以自定義資料之間的間隔符, 可以自定義列數cols

import numpy as np

import linecache

# import os

filename =

"data.dat"

cols =

12# number of column

divided_ch =

' '# divided_character between numbers

defdat_to_matrix

(filename)

:file

=open

(filename)

lines =

file

.readlines(

) rows =

len(lines)

datamat = np.zeros(

(rows, cols)

) row =

0for line in lines:

line = line.strip(

).split(divided_ch)

# strip remove block space in line

datamat[row,:]

= line[:]

row +=

1return datamat

data = dat_to_matrix(filename)

print

(data)

例子

效果

Python 讀取文字檔案到sql server

import json import pymysql import sqlite3 import re import pyodbc import os 載入所需模組 sqlconn pyodbc.connect driver server 伺服器名稱 database 資料庫名稱 連線資料庫 cur...

Python讀取文字檔案

給定c data hello.txt,內容如下 jack hello,how are you?rose i m good.按行讀取 filepath r c data hello.txt with open filepath as txtfile for line in txtfile print ...

讀取文字檔案

void ctestdlg onreadinfo cfile filewrite1 testwrite1.txt cfile modecreate cfile modewrite cfile filewrite2 testwrite2.txt cfile modecreate cfile modew...