Python fileinput模組使用執行個體

來源:互聯網
上載者:User

Python fileinput模組使用執行個體

   這篇文章主要介紹了Python fileinput模組使用執行個體,fileinput模組可以遍曆文字檔的所有行,本文就給出它的使用代碼執行個體,需要的朋友可以參考下

  fileinput模組可以遍曆文字檔的所有行.它的工作方式和readlines很類似,不同點在於,它不是將全部的行讀到列表中而是建立了一個xreadlines對象.

  下面是fileinput模組中的常用函數

  input() #它會返回能夠用於for迴圈遍曆的對象.

  filename() #返回當前檔案的名稱

  lineno() #返回當前(累計)的行數

  filelineno() #返回當前檔案的行數

  isfirstline() #檢查當前行是否是檔案的第一行

   代碼如下:

  #!/bin/env python

  #coding=utf-8

  import fileinput

  import sys

  import glob

  import string

  ''' 處理一個文字檔 '''

  for line in fileinput.input("tab.sh"):

  print line

  '''處理多個文字檔 並輸出行號'''

  for line in fileinput.input(glob.glob("*.sh")):

  if fileinput.isfirstline():

  print "------ reading %s ------n" % fileinput.filename()

  print str(fileinput.lineno()) + " " + line

  例子:

   代碼如下:

  [root@rac1 admin]# python ftest.py

  abc_permission_collection

  abc_user

  abc_user_group_relationship

  ------ reading c.sh ------

  1 c

  2 cc

  3 ccc

  ------ reading tab.sh ------

  4 abc_permission_collection

  5 abc_user

  6 abc_user_group_relationship

  [root@rac1 admin]#

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.