Example
Write yourself a python traversal file script, to the file to be identified for specific processing. There's no technical content, but record it.
The code is as follows |
Copy Code |
#!/usr/bin/python #-*-Coding:utf-8-*- Import Sys Import OS Import Shutil dir = "/mnt/packages" Class Packages: def __init__ (Self,srcdir,desdir): Self.sdir=srcdir Self.ddir=desdir def check (self): Print (' program start ... ') For Dirpath , Dirnames, filenames in Os.walk (self.sdir): #遍历文件 For filename in filenames: Thefile=os.path.join (Dirpath,filename) #文件的绝对地址 Try If Os.path.splitext (thefile) [1]== '. RPM ': Files in #筛选. rpm format #print (' fount RPM Package: ' + thefile) If ' Inspuer ' in Os.popen (' Rpm-qpi ' + thefile). Read (). Rstrip (): Print (' Found error Package: ' + thefile) Shutil.copy (Thefile, Self.ddir) #将错误文件复制到desdir目录 f = open (' List.txt ', ' a ') #将错误文件列表写入到list. txt F.write (filename + ") F.close () Except IOError, err: Print Err Sys.exit ()
if __name__ = = ' __main__ ': Dir=packages ('/mnt/cdrom ', '/mnt/erpm ') #源目录为/mnt/cdrom, the target directory is/mnt/erpm Dir.check () |
example, traversing directory files
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 |
Example
Traverse a folder and delete a specific format file
The code is as follows |
Copy Code |
#!/usr/bin/python #-*-Coding:utf-8-*- Import OS def del_files (path): For Root, dirs, the files in Os.walk (path): For name in Files: If Name.endswith (". tmp"): Os.remove (Os.path.join (root, name)) Print ("Delete File:" + os.path.join (root, name)) # test if __name__ = = "__main__": Path = '/tmp ' Del_files (PATH) |