例子
自己寫的一個Python遍曆檔案指令碼,對查到的檔案進行特定的處理。沒啥技術含量,但是也記錄一下吧。
| 代碼如下 |
複製代碼 |
| #!/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': #篩選.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) |