python练习(遍历所有文件夹及文件)

来源:互联网 发布:金字塔交易 python 编辑:程序博客网 时间:2024/05/24 06:40

遍历所有文件夹及文件,将exe文件的后缀改为zmp,并将文件设置为隐藏文件或系统文件


from sys import stdin
from os import walk
from os.path import join
import win32api,win32con

for (root, dirs, files) in walk('/'):
    #if name in dirs or name in files:
    for filename in files:
        ext=os.path.splitext(filename)[1]
        if(cmp(ext,".exe")==0):
            print(filename)
            newname=filename.replace(ext,".zmp")
            oldpath=root+os.sep+filename
            newpath=root+os.sep+newname
            print "oldpath:"+oldpath+"" 
            print "newpth:"+newpath+"" 
            try: 
                    os.rename(oldpath, newpath)
                    win32api.SetFileAttributes(newpath, win32con.FILE_ATTRIBUTE_HIDDEN)

#win32api.SetFileAttributes(newpath, win32con.FILE_ATTRIBUTE_SYSTEM)
            except ValueError: 
                print "Error when rename the file " + oldpath 
            except NameError: 
                print "Error when rename the file " + oldpath 
            except OSError: 
                print newpath + " The file is already exist!" 

原创粉丝点击