zoukankan      html  css  js  c++  java
  • 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,
  • 相关阅读:
    DFS
    关于memset

    SpringCloud(六)Ribbon负载均衡
    每日算法练习(2020-1-27)
    SpringCloud(五)Eureka Server高可用集群与常见问题
    SpringCloud(四)Eureka服务注册与发现
    SpringCloud(三)常用系统架构技术讲解
    Redis(八)
    Redis(七)
  • 原文地址:https://www.cnblogs.com/Ivyli4258/p/8275330.html
Copyright © 2011-2022 走看看