簡單的Python檔案操作(1) 檔案的開關與讀寫
阿新 • • 發佈:2019-02-08
在python中,使用open函式,可以開啟一個已經存在的檔案,或者建立一個新檔案.
open(檔名,訪問模式) 如例子所示: f = open ('test.txt','w')
訪問模式如下圖:
關閉檔案 : close()
如例子所示:
# 新建一個檔案,檔名為 test.txt f=open('test.txt','w') # 關閉這個檔案 f.close()
檔案的讀寫:
<1>寫資料(write) 使用write()可以完成像檔案寫入資料
(如果檔案不存在就會建立,如果存在那就先清空,然後寫入資料)
f = open('test.txt', 'w') f.write('hello world, i am here!') f.close()
(2) 讀資料(read)
使用read(num)可以從檔案中讀取資料,num表示要從檔案中讀取的資料的長度,單位是位元組(如果沒有傳入num,你們就表示讀取檔案中所有的資料)
f = open('test.txt', 'r')
content = f.read(5)
print(content)
print("-"*30)
content = f.read()
print(content)
f.close()
注意 : 如果open開啟的是一個檔案,那麼可以不用寫開啟的模式,即只寫open('text.txt')
如果使用讀了很多次,那麼後面讀取的資料是從上次讀完後位置開始的
(3) 讀資料(readlines)
就像read沒有引數時一樣,readlines可以按照行的方式把整個檔案中的內容進行一次性讀取,並且返回的是一個列表,其中每一行的資料為一個元素
#coding=utf-8
f = open('test.txt', 'r')
content = f.readlines()
print(type(content))
i=1
for temp in content:
print("%d:%s"%(i, temp))
i+=1
f.close()
<4>讀資料(readline)
#coding=utf-8 f = open('test.txt', 'r') content = f.readline() print("1:%s"%content) content = f.readline() print("2:%s"%content) f.close()