A simple and practical example of the Fileinput module in Python

Source: Internet
Author: User
These days have such a demand, to the user login system information statistics, made a report. When the user logs on successfully, the server will write a log file in the archive like the following: "datetime @ User name @ip", so the journal file is born into one. So, all we have to do is make a calendar of these log files, extract all the login information, and reorganize the data format. Writing an analysis tool in Python is very simple, you would say, using glob to get all the log files, and then open (logfile) for each log file, and then a line of reading, or Os.walk, is also very simple. In fact, the standard library provides another auxiliary module, we can do this work very conveniently, that is fileinput. Below we will use Fileinput to compile all the text files under the D disk, and print out the length of each line:

Import fileinputfrom glob import glob for line in Fileinput.input (Glob (R ' D:/*.txt ')):  print Fileinput.lineno (), U ' file : ', Fileinput.filename (),/      U ' line number: ', Fileinput.filelineno (), u ' length: ', Len (Line.strip ('/n ')) Fileinput.close ()

The code is very simple and straightforward. Input () accepts a list of all file paths to be compiled, returns the file name of the file currently being read through filename (), Filelineno () returns the line number of the currently read row, and Lineno () returns the number (or ordinal) of the currently read row. In fact, the module internally through the Fileinput class to implement the file's calendar reading, input () in the internal creation of an object of the class, when the data row is finished, the Fileinput.close () to close the internal object.

  • 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.