fd = open('/tmp/tmp.txt')
for line in fd: //不建议后面加readlines,节约资源。
print line,
使用while循环遍历文件 #!/usr/bin/python
fd = open('/tmp/tmp.txt') while True: line = fd.readline() if not line: break print line, fd.close()
with open //在python2.6以后的版本才支持 #!/usr/bin/python with open('/tmp/tmp.txt') as fd: while Ture: line = fd.readline() if not line: break print line,
使用with open时,程序代码执行完以后程序会自动关闭文件。