Python Fileinput Module Usage Example

Source: Internet
Author: User
Tags glob

This article mainly introduces the Python fileinput module uses the example, the Fileinput module may traverse the text file all lines, this article gives its use code example, needs the friend to be possible to refer to under

The Fileinput module can traverse all lines of a text file. It works like ReadLines, except that it does not read all the rows to the list but creates a Xreadlines object.

The following are common functions in the Fileinput module

Input () #它会返回能够用于for循环遍历的对象.

FileName () #返回当前文件的名称

Lineno () #返回当前 (cumulative) Number of rows

Filelineno () #返回当前文件的行数

Isfirstline () #检查当前行是否是文件的第一行

The code is as follows:

#!/bin/env python

#coding =utf-8

Import Fileinput

Import Sys

Import Glob

Import string

"Process a text file"

For line in Fileinput.input ("tab.sh"):

Print Line

"" To process multiple text files and to transport the travel number ""

For line in Fileinput.input (Glob.glob ("*.sh")):

If Fileinput.isfirstline ():

Print "------reading%s------N"% fileinput.filename ()

Print str (Fileinput.lineno ()) + "" + Line

Example:

The code is as follows:

[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]#

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.