关于OS模块实例

os模块的所有调用

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径

os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd

 os.curdir  返回当前目录: ('.')

 os.pardir  获取当前目录的父目录字符串名:('..')

 os.makedirs('dirname1/dirname2')    可生成多层递归目录

 os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

 os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname

 os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

 os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

 os.remove()  删除一个文件

 os.rename("oldname","newname")  重命名文件/目录

 os.stat('path/filename')  获取文件/目录信息

 os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"

 os.linesep    输出当前平台使用的行终止符,win下为" ",Linux下为" "

 os.pathsep    输出用于分割文件路径的字符串

 os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

 os.system("bash command")  运行shell命令,直接显示

 os.environ  获取系统环境变量

 os.path.abspath(path)  返回path规范化的绝对路径

 os.path.split(path)  将path分割成目录和文件名二元组返回

 os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素

 os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素

 os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False

 os.path.isabs(path)  如果path是绝对路径,返回True

 os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False

 os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False

 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

 os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间

 os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

  

#设置环境路径

file_path=os.path.dirname(os.path.abspath(__file__))
sys.path.append(file_path)

#显示当前文件的绝对路径,含文件名。

print(os.path.abspath(__file__))
print(sys.argv[0])

#显示当前文件的绝对路径,不含文件名。

print(os.getcwd())
print(os.path.abspath(os.curdir))

#关于os.path.join的用法,创建目录下的文件。

path1=os.path.join(r".in","bin1")
path2=os.path.join(path1+r" ext.txt")
print(path1,path2)
os.makedirs(path1)
new_file=open(path2,"w")
new_file.close()

stat 系统调用时用来返回相关文件的系统状态信息的。

首先我们看一下stat中有哪些属性:

>>> import os
>>> print os.stat("/root/python/zip.py")
(33188, 2033080, 26626L, 1, 0, 0, 864, 1297653596, 1275528102, 1292892895)
>>> print os.stat("/root/python/zip.py").st_mode   #权限模式
33188
>>> print os.stat("/root/python/zip.py").st_ino   #inode number
2033080
>>> print os.stat("/root/python/zip.py").st_dev    #device
26626
>>> print os.stat("/root/python/zip.py").st_nlink  #number of hard links
1
>>> print os.stat("/root/python/zip.py").st_uid    #所有用户的user id
0
>>> print os.stat("/root/python/zip.py").st_gid    #所有用户的group id
0
>>> print os.stat("/root/python/zip.py").st_size  #文件的大小,以位为单位
864
>>> print os.stat("/root/python/zip.py").st_atime  #文件最后访问时间
1297653596
>>> print os.stat("/root/python/zip.py").st_mtime  #文件最后修改时间
1275528102
>>> print os.stat("/root/python/zip.py").st_ctime  #文件创建时间
1292892895

 正如你上面看到的,你可以直接访问到这些属性值。

好了,下面我来看看python中的stat模块,先看看自带的例子:

复制代码
import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)
复制代码

可以这么理解,os.stat是将文件的相关属性读出来,然后用stat模块来处理,处理方式有多重,就要看看stat提供了什么了。

1.  可以对st_mode做相关的判断,如是否是目录,是否是文件,是否是管道等。

先看一下处理os.stat返回的st_mode结果的函数,就想上面的例子中的一样,这些函数可以做出判断:

复制代码
if stat.S_ISREG(mode):           #判断是否一般文件
   print 'Regular file.'
elif stat.S_ISLNK (mode):         #判断是否链接文件
   print 'Shortcut.'
elif stat.S_ISSOCK (mode):        #判断是否套接字文件    
   print 'Socket.'
elif stat.S_ISFIFO (mode):        #判断是否命名管道
   print 'Named pipe.'
elif stat.S_ISBLK (mode):         #判断是否块设备
   print 'Block special device.'
elif stat.S_ISCHR (mode):         #判断是否字符设置
  print 'Character special device.'
elif stat.S_ISDIR (mode):         #判断是否目录
  print 'directory.'
##额外的两个函数
stat.S_IMODE (mode): #返回文件权限的chmod格式
  print 'chmod format.'

stat.S_IFMT (mode): #返回文件的类型
  print 'type of fiel.'
 
复制代码

2.   还有一些是各种各样的标示符,这些标示符也可以在os.chmod中使用,下面附上这些标示符的说明:

复制代码
    stat.S_ISUID: Set user ID on execution.                      不常用

    stat.S_ISGID: Set group ID on execution.                    不常用

    stat.S_ENFMT: Record locking enforced.                                          不常用

    stat.S_ISVTX: Save text image after execution.                                在执行之后保存文字和图片

    stat.S_IREAD: Read by owner.                                                           对于拥有者读的权限

    stat.S_IWRITE: Write by owner.                                                         对于拥有者写的权限

    stat.S_IEXEC: Execute by owner.                                                       对于拥有者执行的权限

    stat.S_IRWXU: Read, write, and execute by owner.                          对于拥有者读写执行的权限

    stat.S_IRUSR: Read by owner.                                                            对于拥有者读的权限

    stat.S_IWUSR: Write by owner.                                                          对于拥有者写的权限

    stat.S_IXUSR: Execute by owner.                                                       对于拥有者执行的权限

    stat.S_IRWXG: Read, write, and execute by group.                                 对于同组的人读写执行的权限

    stat.S_IRGRP: Read by group.                                                             对于同组读的权限

    stat.S_IWGRP: Write by group.                                                           对于同组写的权限

    stat.S_IXGRP: Execute by group.                                                        对于同组执行的权限

    stat.S_IRWXO: Read, write, and execute by others.                          对于其他组读写执行的权限

    stat.S_IROTH: Read by others.                                                           对于其他组读的权限

    stat.S_IWOTH: Write by others.                                                         对于其他组写的权限

    stat.S_IXOTH: Execute by others.                                                      对于其他组执行的权限
复制代码

例子:我想获得某个文件的属性信息,并查看他的权限信息,用chmod的格式显示出来。

复制代码
>>> import stat
>>> import os
>>> st = os.stat('sig.txt')
>>> mode = st.st_mode
>>> stat.S_IFMT(mode)
32768
>>> stat.S_IMODE(mode)
438
>>> print oct(stat.S_IMODE(mode))#oct 是转换为八进制
0666
复制代码
原文地址:https://www.cnblogs.com/phoenix-mountain/p/12945787.html