0%

[Python] read() vs. readline() vs. readlines()

在 Python 中讀取檔案有三種常用的方法: read(), readline()readlines(), 這裡紀錄一下這三種方法的差別及使用方式。

read()

read([size])這個方法是從檔案當前位置起讀取 size 個字,若沒有參數 size,則表示讀取到檔案結束為止。

範例文件 (test.txt) :

1
2
3
Hi, 123
Hello world
中文

使用方法:

1
2
3
4
5
6
7
# test.py
fp = open('test.txt', 'r', encoding='utf-8')
content = fp.read()
fp.close()

print(content)
print(type(content))

輸出:

1
2
3
4
5
6
$ python3 test.py
Hi, 123
Hello world
中文

<class 'str'>

readline()

每次讀出一行內容,讀取時占用的記憶體較小,比較適合大檔案。

使用方法:

1
2
3
4
5
6
7
8
9
10
# test.py
fp = open('test.txt', 'r', encoding='utf-8')

line = fp.readline()
while line:
print(line)
print(type(line))
line = fp.readline()

fp.close()

輸出:

1
2
3
4
5
6
7
8
9
10
$ python3 test.py
Hi, 123

<class 'str'>
Hello world

<class 'str'>
中文

<class 'str'>

readlines()

一次讀取整個檔案的所有行,保存在一個 list 中,每行作為一個元素,讀取大檔案會比較占記憶體。

使用方法:

1
2
3
4
5
6
7
8
9
# test.py
fp = open('test.txt', 'r', encoding='utf-8')
lines = fp.readlines()
print(type(lines))

for line in lines:
print(line)

fp.close()

輸出:

1
2
3
4
5
6
7
8
$ python3 test.py
<class 'list'>
Hi, 123

Hello world

中文