Simple and practical example of the fileinput module in Python, pythonfileinput

Source: Internet
Author: User
Tags glob

Simple and practical example of the fileinput module in Python, pythonfileinput

In the past few days, we have to collect statistics on User Login system information and make a report. When a user logs in successfully, the server will write a record in the following format to the log file: "Date and Time @ username @ IP". Such a log file is born into one. Therefore, we only need to edit these log files, extract all login information, and reorganize the data format. Writing an analysis tool in python is very simple. You will say that using glob to get all log files, then open each log file (logfile), and read one row at a time; or use OS. it is also very simple. In fact, the standard library provides another auxiliary module, which is fileinput. Next we will use fileinput to compile all text files on drive D and print the length of each row:
 

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 clear. Input () accepts the list of all file paths for calendar editing, returns the file name of the file currently being read through filename (), and returns the row number of the currently read row through filelineno, lineno () returns the number (or serial number) of rows currently read ). In fact, the module uses the FileInput class to implement file calendar reading. input () creates an object of this class internally. After data rows are processed, fileinput is used. close () to close this 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.