在python可以處理文字檔中的資訊,可以一次讀取全部的內容,也可以一行一行的讀取。
Python內建函式open()可以開啟指定檔案,可以讀取、寫入和修改檔案內容。
open():開啟檔案:open(filename[,mode])
filename:
filename 要讀寫的檔案名稱 (字串型態、不可省略)。
mode:
mode 開啟檔案的模式 (字串型態、可以省略,預設為讀取r)。
通常都是用r、w、a來控制。
檔案讀寫模式如下:
| 字元 | 說明 |
|---|---|
| r | 只讀取檔案(唯讀)。檔案必須存在。 |
| r+ | 讀取寫入檔案(讀寫)。不會新建檔案,檔案必須存在,寫入會覆蓋原本內容。 |
| w | 新建寫入檔案(只寫)。文件內容清零。 |
| w+ | 新建讀取寫入檔案(讀寫)。文件內容清零。 |
| a | 寫入檔案(只寫)。新增在檔案後面,不會覆蓋原本的。 |
| a+ | 允許新增與讀取(讀寫)。新增在檔案後面,不會覆蓋原本的。 |
close():關閉檔案,關閉後就不能進行讀寫動作。# 使用w+
f = open("test.txt", "w+")
f.write( "123\n")
f.close()
# 使用r+
f = open("test.txt", "r+")
f.write( "456\n")
f.close()
# 使用a+
f = open("test.txt", "a+")
f.write( "789\n")
f.close()
這時候就會出現一個txt檔案,來看一下內容吧!
所以可以知道 r+ 是會覆蓋檔案,a+ 則是附加在檔案後面!
再來試試輸入一次試試看r+如何覆蓋檔案。
# 使用w+
f = open("test.txt", "w+")
f.write( "try123\n")
f.close()
# 使用r+
f = open("test.txt", "r+")
f.write( "456\n")
f.close()
# 使用a+
f = open("test.txt", "a+")
f.write( "789\n")
f.close()
結果:
r+寫入了123\n 一共是4個元素,並且加在檔案最前面,
因此他蓋掉了w+ 的前4個元素,所以就只剩下23。
來創建個簡單的txt檔案吧!
檔名= hello.txt
Hello
World
123
456
789
把檔案讀取進來後,接著就是將檔案內容放進變數裡。
這裡有五種方法:
read()
readline()
readlines()
ITER
linecache.getline()
read([size])方法:f = open('hello.txt', 'r')
lines = f.read() #沒指定size
print(lines)
print(type(lines))
f.close()
結果:
Hello
World
123
456
789
<class 'str'>
指定size(10)=>印出前10個字元
範例:
f = open('hello.txt', 'r')
lines1 = f.read(10)
print(lines1)
f.close()
結果:
Hello
Worl
readline()方法:replace('\n','') 將換行符號去掉f = open('hello.txt', 'r')
line = f.readline().replace('\n','') #去掉換行
while line:
print(line)
line = f.readline().replace('\n','') #去掉換行
f.close()
結果:
Hello
World
123
456
789
readlines()方法:with則不須使用f.close()with open('hello.txt','r') as f:
lines = f.readlines()
print(lines)
或者
f = open('hello.txt', 'r')
lines = f.readlines()
print(lines)
f.close() #a沒有使用with就需要關閉檔案
上面兩個方法的結果是一樣的:
['Hello\n', 'World\n', '123\n', '456\n', '789']
\n => 換行指令也會一起存。
將List內容分別印出:
for line in lines:
#line = line.split('\n')[0] #去掉換行
line = line.replace('\n','') #去掉換行
print(line)
split('\n')[0],去掉換行之後取List[0]的值
replace('\n',''),去掉換行
結果:
Hello
World
123
456
789
with方法類似,印出的結果也一樣f = open('hello.txt', "r")
for line in iter(f):
print(line)
f.close()
結果:
Hello
World
123
456
789
import linecache
line = linecache.getline('hello.txt',2)
print(line)
結果:
World
王者歸來:精通物聯網及Python / 作者: 劉凱