首先,获取文件对象
代码语言:javascript复制file = "F://content.txt"
f = open(file, 'r', encoding='utf-8')
list = f.readlines()
方法一:直接打印
代码语言:javascript复制# 方法1:直接打印
print(list)
方法二::while循环
代码语言:javascript复制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循环
代码语言:javascript复制# 方法3:for循环
for i in list:
print(i.strip())
所有代码:
代码语言:javascript复制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())
测试文本:
代码语言:javascript复制bbb aa dd
cc aa cc
aa dd ee
dfs dfs dfs
运行结果: