Introduction to the Python fileinput module, pythonfileinput

Source: Internet
Author: User

Introduction to the Python fileinput module, pythonfileinput

The fileinput module allows you to process one or more text files. You can use the for loop to read all rows of one or more text files. It works in a similar way as readlines. The difference is that it creates an xreadlines object instead of reading all rows into the list.

The following are common functions in the fileinput module:

Input () # returns the object filename () that can be used for loop traversal # returns the name of the current file lineno () # returns the number (or serial number) of currently read rows filelineno () # Return the row number isfirstline () of the currently read row # Check whether the current row is the first row of the file

Create the test file test.txt:

# cat > test.txt << EOFHello,Pythonwww.jb51.netThis is a test fileEOF

Use fileinput to replace the file content, for example, file_input.p (note that the file name should not be written as 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: The standard output will be redirected to the open file; backup = '_ Bak': the backup suffix ends with _ bak before the file content is replaced; in addition, fileinput is called. remember fileinput after input. close ().
The execution result is as follows:

# Python file_input.py # Run file_input.py # ls test.txt * test.txt _ bak # cat test.txt Hello, LinuxEyewww. Metadata is a test file # cat test.txt _ bakHello, Pythonwww. jb51.netThis is a test file

Other tests:

>>> import fileinput>>> for line in fileinput.input('test.txt'):...   print fileinput.filename(),fileinput.lineno(),fileinput.filelineno()...test.txt 1 1test.txt 2 2test.txt 3 3
>>> import fileinput>>> for line 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.