python讀取txt文件的方法:首先打開文件,代碼為【f = open('/tmp/test.txt')】;然后進行讀取,代碼為【<open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc】。
本教程操作環(huán)境:windows7系統(tǒng)、python3.9版,該方法適用于所有品牌電腦。
python讀取txt文件的方法:
一、文件的打開和創(chuàng)建
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!nhello world!n' >>> f <open file '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>
二、文件的讀取
步驟:打開 — 讀取 — 關(guān)閉
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!nhello world!n' >>> f.close()
讀取數(shù)據(jù)是后期數(shù)據(jù)處理的必要步驟。.txt是廣泛使用的數(shù)據(jù)文件格式。一些.csv, .xlsx等文件可以轉(zhuǎn)換為.txt 文件進行讀取。我常使用的是Python自帶的I/O接口,將數(shù)據(jù)讀取進來存放在list中,然后再用numpy科學(xué)計算包將list的數(shù)據(jù)轉(zhuǎn)換為array格式,從而可以像MATLAB一樣進行科學(xué)計算。
下面是一段常用的讀取txt文件代碼,可以用在大多數(shù)的txt文件讀取中
filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt文件和當前腳本在同一目錄下,所以不用寫具體路徑 pos = [] Efield = [] with open(filename, 'r') as file_to_read: while True: lines = file_to_read.readline() # 整行讀取數(shù)據(jù) if not lines: break pass p_tmp, E_tmp = [float(i) for i in lines.split()] # 將整行數(shù)據(jù)分割處理,如果分割符是空格,括號里就不用傳入?yún)?shù),如果是逗號, 則傳入‘,'字符。 pos.append(p_tmp) # 添加新讀取的數(shù)據(jù) Efield.append(E_tmp) pass pos = np.array(pos) # 將數(shù)據(jù)從list類型轉(zhuǎn)換為array類型。 Efield = np.array(Efield) pass
例如下面是將要讀入的txt文件
經(jīng)過讀取后,在Enthought Canopy的variable window查看讀入的數(shù)據(jù), 左側(cè)為pos,右側(cè)為Efield。
相關(guān)免費學(xué)習(xí)推薦:python視頻教程