Python Fileinput Module Usage Introduction

Source: Internet
Author: User
The Fileinput module provides the ability to work with one or more text files, and you can read all lines of one or more text files by using a For loop. It works in a similar way to 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 ()   #返回当前已经读取的行的数量 (or ordinal) Filelineno () # Returns the line number of the currently read Line Isfirstline () #检查当前行是否是文件的第一行

To create a test file Test.txt:

# cat > Test.txt << eofhello,Pythonwww.jb51.netThis is a test fileeof

Use Fileinput to implement the file content substitution, such as: FILE_INPUT.P ( note The file name, do not write fileinput.py)

#!/usr/bin/env pythonimport fileinputfor Line in Fileinput.input (' Test.txt ', backup= ' _bak ', inplace=1):  Print Line.replace (' Python ', ' Linuxeye '), Fileinput.close ()

Inplace=1: Standard output will be redirected to open file, backup= ' _bak ',: Backup suffix to _bak end before replacing file contents, and Fileinput.input () after calling Fileinput.close ().
The results of the implementation are as follows:

# python file_input.py #执行file_input. py# ls test.txt*test.txt Test.txt_bak # cat Test.txthello,linuxeyewww.jb51.netthis is a test file # cat test.txt_bakhello,pythonwww.jb51.netthis is a test file

Other tests:

>>> Import fileinput>>> in Fileinput.input (' Test.txt '): ...   Print Fileinput.filename (), Fileinput.lineno (), Fileinput.filelineno () ... test.txt 1 1test.txt 2 2test.txt 3 3
>>> Import fileinput>>> in Fileinput.input (' Test.txt '): ...   If Fileinput.isfirstline (): ...     Print Line,...   else:     ... Break ... Hello,linuxeye
  • 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.