Python處理檔案相關操作
阿新 • • 發佈:2019-02-03
open() 方法
Python open()
方法用於開啟一個檔案,並返回檔案物件,在對檔案進行處理過程都需要使用到這個函式,如果該檔案無法被開啟,會丟擲 OSError。
注意:使用 open()
方法一定要保證關閉檔案物件,即呼叫 close()
方法。
open()
函式常用形式是接收兩個引數:檔名(file)和模式(mode)。
完整的語法格式為:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 引數說明: file: 必需,檔案路徑(相對或者絕對路徑)。 mode: 可選,檔案開啟模式 buffering: 設定緩衝 encoding: 一般使用utf8 errors: 報錯級別 newline: 區分換行符 closefd: 傳入的file引數型別 opener:
>>> with open('F://lixu.txt','r') as f:
... print(f.read())
...
大家好,我叫李*!
>>> try:
... f = open('F://lixu.txt',mode='r')
... print(f.read())
... finally:
... if f:
... f.close()
...
大家好,我叫李*!
def readData(self,datafile = None): """ read the data from the data file which is a data set """ self.datafile = datafile or self.datafile self.data = [] for line in open(self.datafile): userid,itemid,record,_ = line.split() self.data.append((userid,itemid,int(record)))
read()
read()
方法用於從檔案讀取指定的位元組數,如果未給定或為負則讀取所有。
>>> with open('F://lixu.txt','r') as f:
... print(f.read())
...
大家好,我叫李*!
readline()
readline()
方法用於從檔案讀取整行,包括 “\n” 字元。如果指定了一個非負數的引數,則返回指定大小的位元組數,包括 “\n” 字元。
檔案內容: 1:www.runoob.com 2:www.runoob.com 3:www.runoob.com 4:www.runoob.com 5:www.runoob.com # 開啟檔案 fo = open("runoob.txt", "rw+") print "檔名為: ", fo.name line = fo.readline() print "讀取第一行 %s" % (line) line = fo.readline(5) print "讀取的字串為: %s" % (line) # 關閉檔案 fo.close() 檔名為: runoob.txt 讀取第一行 1:www.runoob.com 讀取的字串為: 2:www
readlines()
readlines()
方法用於讀取所有行(直到結束符 EOF)並返回列表,該列表可以由 Python 的 for… in … 結構進行處理。
如果碰到結束符 EOF 則返回空字串。
def file2matrix(filename):
"""
從檔案中讀入訓練資料,並存儲為矩陣
"""
fr = open(filename)
arrayOlines = fr.readlines()
numberOfLines = len(arrayOlines) #獲取 n=樣本的行數
returnMat = zeros((numberOfLines,3)) #建立一個2維矩陣用於存放訓練樣本資料,一共有n行,每一行存放3個數據
classLabelVector = [] #建立一個1維陣列用於存放訓練樣本標籤。
index = 0
for line in arrayOlines:
# 把回車符號給去掉
line = line.strip()
# 把每一行資料用\t分割
listFromLine = line.split('\t')
# 把分割好的資料放至資料集,其中index是該樣本資料的下標,就是放到第幾行
returnMat[index,:] = listFromLine[0:3]
# 把該樣本對應的標籤放至標籤集,順序與樣本集對應。
classLabelVector.append(int(listFromLine[-1]))
index += 1
return returnMat,classLabelVector
區別
>>> f = open('F://lixu.txt',mode='r')
>>> line2 = f.readline()
>>> print(line2)
大家好,我叫李*!
>>> f = open('F://lixu.txt',mode='r')
>>> line = f.read()
>>> print(line)
大家好,我叫李*!
啦啦啦
>>> f = open('F://lixu.txt',mode='r')
>>> line = f.readlines()
>>> print(line)
['大家好,我叫李*!\n', '\n', '啦啦啦\n', '\n', '\n']