天天看点

python 常用功能锦集

环境:linux

版本:python 2.6.6 (r266:84292, apr 11 2011, 15:52:27)

(1)如何获取指定文件的属主:

def getowner(path2):

import os

import pwd

return pwd.getpwuid(os.stat(path2).st_uid).pw_name

(2)如何递归列出指定目录的所有file(不包括目录):

def listfiles(path2):

        import os

        tmp=os.walk(path2)

        full_files=[]

        for root,dirs, files in tmp:

                for file in files:

                        full_files.append(os.path.join(root,file))

        return full_files

(3)如何获取指定文件的权限,如755

python 常用功能锦集

def get_power(path3):  

''''' 

path3 is directory or regular file 

'''  

    import os  

    return oct(os.stat(path3)[0])[-3:]  

(4)如何设置权限

(类似于 chmod 755 /home/user2)

python 常用功能锦集

def chmod(path4,str_power):  

    if not os.path.exist(path4):  

        return 4 #file does not exist  

    os.chmod(path4,int(str_power,8))