首先,获取文件对象

file = "F://content.txt"
f = open(file, 'r', encoding='utf-8')
list = f.readlines()

方法一:直接打印

# 方法1:直接打印
print(list)

方法二::while循环

print('----------方法2:while循环1----------------')
# 方法2:while循环
f = open(file, 'r', encoding='utf-8')
while True:
    line = f.readline()
    if len(line)==0:
        break
    print(line.strip('\n'))
print('----------方法2:while循环2----------------')
while length>0:
    print(list[i][:-1])
    i+=1
    length-=1

方法三:for循环

# 方法3:for循环
for i in list:
    print(i.strip())

所有代码:

file = "F://content.txt"
f = open(file, 'r', encoding='utf-8')
list = f.readlines()
print('-------------方法1:直接打印----------------')
# 方法1:直接打印
print(list)
length = len(list)
i=0
print('----------方法2:while循环1----------------')
# 方法2:while循环
file = "F://content.txt"
while True:
    line = f.readline()
    if len(line)==0:
        break
    print(line.strip('\n'))
print('----------方法2:while循环2----------------')
while length>0:
    print(list[i][:-1])
    i+=1
    length-=1
print('---------方法3:for循环-------------------')
# 方法3:for循环
for i in list:
    print(i.strip())

测试文本:

bbb aa  dd
cc  aa  cc
aa  dd  ee
dfs dfs dfs

运行结果:

python读取文件(三种方法)_测试文本