#!/usr/bin/python# -*- coding: utf-8 -*-import sysimport osimport shutildir = "/mnt/Packages"class Packages: def __init__(self,srcdir,desdir): ...
#!/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): www.111cn.Net #遍歷文件 for filename in filenames: thefile=os.path.join(dirpath,filename) #文件的絕對地址 try: if os.path.splitext(thefile)[1]=='.rpm': #篩選.rpm格式的文件 #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,目標目錄為/mnt/erpm dir.check()
例子,遍歷目錄下文件 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 例子 遍歷文件夾並刪除特定格式文件 #!/usr/bin/python # -*- coding: utf-8 -*- import os def del_files(path): for root , dirs, 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)