Python for循环文件

for 循环遍历文件:打印文件的每一行

#!/usr/bin/env python
fd = open('/tmp/hello.txt')
  for line in fd:
    print line,
注意:这里for line in fd,其实可以从fd.readlines()中读取,但是如果文件很大,那么就会一次性读取到内存中,非常占内存。
而这里fd存储的是对象,只有我们读取一行,它才会把这行读取到内存中,建议使用这种方法。
 
  while循环遍历文件:
#!/usr/bin/env python
fd = open('/tmp/hello.txt')
while True:
  line = fd.readline()
  if not line:
    break
    print line,
fd.close()

 如果不想每次打开文件都关闭,可以使用with关键字,2.6以上版本支持with读取 with open('/tmp/hello.txt') as fd: 然后所有打开文件的操作都需要缩进,包含在with下才行

with open('/tmp/hello.txt') as fd:
while True:
  line = fd.readline()
  if not line:
    break
    print line,
原文地址:https://www.cnblogs.com/Ivyli4258/p/8275330.html