您的位置:首页 > 其它

使用while循环遍历文件

2016-09-05 16:19 323 查看
/* 使用while循环遍历文件*/
[root@localhost test1]# vim 17.py
//add
#!/usr/bin/python

ll = open('/tmp/1.txt')
while True:
line = ll.readline()
if not line:
break
print line,

[root@localhost test1]# python 17.py
abc
sjdh


/* 另外一种写法,(常用),省去了去把变量关闭 */
[root@localhost test1]# vim 17.py
//add
#!/usr/bin/python

with open('/tmp/1.txt') as ll:
while True:
line = ll.readline()
if not line:
break
print line,

/*
  这里的 "ll" -- 返回的对象
  
  对象”ll“中 有ll.readline() 这个方法

  将方法中获得的值 都存在 line这个变量里

  判断line是不是空 -是 -break
           -不是 -print line
*/

[root@localhost test1]# python 17.py
abc
sjdh
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: