Python fileinput Module Use introduction _python

Source: Internet
Author: User

The Fileinput module provides the ability to work with one or more text files, and you can read all the rows of one or more text files by using a For loop. It works the same way as 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 () #返回当前读取的行的行号
isfirstline () #检查当前行是否是文件的第一行

To create a test file Test.txt:

# cat > Test.txt << EOF
Hello,Python
www.jb51.net This is
a test file
EOF

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

#!/usr/bin/env python
import fileinput for 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 remember to 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.txt
Hello, Linuxeye
www.jb51.net This are
a test file
 
# cat Test.txt_bak
hello,python
www.jb51.net
This 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 1
test.txt 2 2
test.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.