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.