1. 程式人生 > 實用技巧 >Python:讀取檔案內容<file>.read()、<file>.readline()和<file>.readlines()

Python:讀取檔案內容<file>.read()、<file>.readline()和<file>.readlines()

Python:讀取檔案內容<file>.read()、<file>.readline()和<file>.readlines()

<file>.read()

將檔案的全部剩餘內容作為一個大字元返回

例子

# names.txt
John Zelle
Zaphod Beeblebrox
Guido VanRossum
Yu Zhou
Yu Zhou
Yu Zhou
Yu Zhou
Li Daqiao
# example01.py
a = 0
infile = open('names.txt')
for line in infile:
    print(line, end='')
    a = a+1
    if a == 3:
        break
print('\n', end='')
allchr = infile.read()
print(allchr)
# 輸出結果如下
# John Zelle
# Zaphod Beeblebrox
# Guido VanRossum

# Yu Zhou
# Yu Zhou
# Yu Zhou
# Yu Zhou
# Li Daqiao

<file>.readline()

每次讀取檔案的一行作為字串返回

例子

# example02.py
a = 0
infile = open('names.txt')
for line in infile:
    print(line, end='')
# 輸出結果如下
# John Zelle
# Zaphod Beeblebrox
# Guido VanRossum
# Yu Zhou
# Yu Zhou
# Yu Zhou
# Yu Zhou
# Li Daqiao

<file>.readlines()

返回檔案中剩餘的行的列表,列表的每一項都是檔案中某的一行的字串,包括結尾處的換行符

例子

# # example03.py
infile = open('names.txt')
a = infile.readlines()
print(a[2:-1])infile = open('names.txt')
a = infile.readlines()
print(a[2:-1])
print('\n')

for i in range(2,6,1):
    print(a[i], end='')
# 輸出結果如下
# ['Guido VanRossum\n', 'Yu Zhou\n', 'Yu Zhou\n', 'Yu Zhou\n', 'Yu Zhou\n']
# 
# 
# Guido VanRossum
# Yu Zhou
# Yu Zhou
# Yu Zhou
#