Python:读取文件内容<file>.read()、<file>.readline()和<file>.readlines()

Python:读取文件内容<file>.read()、<file>.readline()和<file>.readlines()

此处先略过不看,下面例子需要用到的文件names.txt如下

# names.txt
John Zelle
Zaphod Beeblebrox
Guido VanRossum
Yu Zhou
Yu Zhou
Yu Zhou
Yu Zhou
Li Daqiao

<file>.read()

文件的全部剩余内容作为一个大字符返回

例子

# 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()

每次读取文件的一行作为字符串返回

例子1

# 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

例子2,每次读取完一行后,下一次将自动读取下一行内容

# example03.py
infile = open('../names.txt')
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
print(line1, end='')
print(line2, end='')
print(line3, end='')
print(line4, end='')
# 输出结果如下
# John Zelle
# Zaphod Beeblebrox
# Guido VanRossum
# Yu Zhou
# 

<file>.readlines()

返回文件中剩余的行的列表,列表的每一项都是文件中某的一行的字符串,包括结尾处的换行符

例子

# # example04.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
# 
posted on 2021-01-20 18:15  摸鱼time  阅读(410)  评论(0编辑  收藏  举报