Linux servers have CentOS, fedora, etc., are pre-installed Python, version from 2.4 to 2.5, and the Windows type of server is also most installed Python, so as long as the local computer write a script, upload to the corresponding machine, at run time to modify parameters.
Python operations files and folders use the os Library, and the following code mainly uses several functions:
Os.listdir: list the files and folders under the directory
Os.path.join: Stitching to get the full path of a file / folder
Os.path.isfile: Determine if it is a file
Os.path.splitext: Remove a sub-section from a name
Here is the code for the directory operation
The code is as follows |
Copy Code |
Def search (folder, filter, Allfile): Folders = Os.listdir (folder) For name in folders: Curname = os.path.join (folder, name) Isfile = Os.path.isfile (curname) If Isfile: ext = Os.path.splitext (curname) [1] Count = Filter.count (EXT) If count>0: cur = myfile () Cur.name = Curname Allfile.append (cur) Else Search (Curname, filter, Allfile) Return Allfile |
In the return of various information of the file, use the custom class Allfile to save the file information, in the program only use the full path of the file, if you need to record the size of the file, time, type and other information, you can imitate code to expand.
The code is as follows |
Copy Code |
Class MyFile: def __init__ (self): Self.name = "" |
Once you have an array of stored file information, you can also save it in XML format, the code below, which you need to import from document when you use it xml.dom.minidom
Here is the code saved as XML
The code is as follows |
Copy Code |
def generate (Allfile, XML): doc = Document () Root = doc.createelement ("root") Doc.appendchild (Root) For myfile in Allfile: File = doc.createelement ("file") Root.appendchild (file) Name = Doc.createelement ("name") File.appendchild (name) Namevalue = Doc.createtextnode (myfile.name) Name.appendchild (Namevalue) Print Doc.toprettyxml (indent= "") F = open (XML, ' A + ') F.write (Doc.toprettyxml (indent= "")) F.close () |
The code is executed as follows
code as follows |
Copy code |
if __name__ == ' __main__ ': folder = /usr/local/apache/htdocs filter = [". html", ". htm", ". php"] allfile = [] allfile = search (folder, filter, allfile) len = len (allfile) print "found: " + str ( Len) + " files" xml = "Folder.xml" generate (allfile, xml) |
in linux command line state, execute python filesearch.py folder.xml the file.
If you want to run the program in Windows , you need to change the folder variable to a format under Windows, such as c \ Apache2htdocs, and then execute c:python25python.exe filesearch.py(This assumes that python The installation directory is c:python25)
Python file directory traversal saved as XML file code