• 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,
  • 相关阅读:
    Texture转Texture2D
    虚拟化 -- kvm简介
    虚拟化
    数据库
    openstack共享组件(1)------ NTP 时间同步服务
    openstack
    Linux基础命令
    第七章 Python文件操作
    第六章 Python流程控制
    老吴Python宝典之——Python字典&集合(第五章 )
  • 原文地址:https://www.cnblogs.com/Ivyli4258/p/8275330.html
Copyright © 2020-2023  润新知