zoukankan      html  css  js  c++  java
  • os模块

    一、os模块概述

    Python os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。如果我们要操作文件、目录,可以在命令行下面输入操作系统提供的各种命令来完成。比如dir、cp等命令。其实操作系统提供的命令只是简单地调用了操作系统提供的接口函数,python内置的os模块也可以直接调用操作系统提供的接口函数。

      

    二、os模块常用方法

    1. os.name:

    判断现在正在实用的平台,Windows 返回 ‘nt'; Linux 返回’posix'

     
    1. >>> os.name  
    2. 'posix'  

    2. os.uname():

    返回更详细的系统信息

     
    1. >>> os.uname()  
    2. ('Linux', 'kali', '3.18.0-kali3-686-pae', '#1 SMP Debian 3.18.6-1~kali2 (2015-03-02)', 'i686')  

    3. os.getcwd()

    函数得到当前工作目录,即当前Python脚本工作的目录路径。

    1. >>> os.getcwd()  
    2. '/usr/peic'  


    4. os.listdir()

    返回指定目录下的所有文件和目录名。

    >>> os.listdir(os.getcwd())
    ['python'

    5. os.remove()

    删除一个文件

    6. os.system()

    运行shell命令。

    >>> os.system('dir')
    python
    0
    

    7. os.sep和os.linesep

    给出当前操作系统特定的路径分割符和使用的行终止符

    >>> os.sep
    '/'
    >>> os.linesep         #Windows使用'
    ',Linux使用'
    '而Mac使用'
    '。
    '
    '      
    

    8、os.path.split()

    返回一个路径的目录名和文件名

    >>> os.path.split('/usr/peic/python/TestTxt.txt')
    ('/usr/peic/python', 'TestTxt.txt'

    9、os.path.isfile()和os.path.isdir()

    分别检验给出的路径是一个文件还是目录。

    >>> os.path.isdir('/usr/peic')
    True
    >>> os.path.isfile('/usr/peic')
    False
    >>> os.path.isfile('/usr/peic/python/TestTxt.txt')
    True
    

    10、os.path.exists()

    检验给出的路径是否真地存在

    >>> os.path.exists('/usr/peic/python/TestTxt.txt')
    True
    >>> os.path.exists('/usr/peic/python/TestTxt')
    Fals

    11、os.path.abspath(name)

    获得绝对路径

    1. >>> os.path.exists('./python/TestTxt.txt')  
    2. True  
    3. >>> os.path.abspath('./python/TestTxt.txt')  
    4. '/usr/peic/python/TestTxt.txt'  

    12、os.path.normpath(path):

    规范path字符串形式

    1. >>> os.path.normpath('./python')  
    2. 'python'  

    13、os.path.getsize(name)

    获得文件大小,如果name是目录返回0L

    1. >>> os.path.getsize('./python/TestTxt.txt')  
    2. 13L  
    3. >>> os.path.getsize('./python')  
    4. 4096L  

    14、os.path.splitext()

    分离文件名与扩展名

    >>> os.path.splitext('a.txt')
    ('a', '.txt')

    15、os.path.join(path,name)

    连接目录与文件名或目录

    >>> os.path.join('./python','a.txt')
    './python/a.txt'
    

    16、os.path.basename(path)

    返回文件名

    >>> os.path.basename('./python/a.txt')
    'a.txt

    17、os.path.dirname(path):返回文件路径

    >>> os.path.dirname('./python/a.txt')
    './python'
    

    三、例子(自己一个调试错误的说明)

    例子说明:要求能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

    注:dir_l()函数与本例无关

     
    1. #---coding:utf-8  
    2.   
    3. __author__ = 'peic'  
    4.   
    5. import os  
    6.   
    7. def dir_l(dir=os.getcwd()):  
    8.       
    9.     'This function list all content in the current directory'  
    10.       
    11.     #获取目录下的所有文件和目录名  
    12.     contentList = os.listdir(dir)  
    13.       
    14.     #获得目录  
    15.     dirList = [x for x in contentList if os.path.isdir(x)]  
    16.     print('Directory included in current dir: ')  
    17.     if dirList == []:  
    18.         print('  Current directory has no directory!')  
    19.     for x in dirList:  
    20.         print('  %s' %x)  
    21.       
    22.     #获得文件  
    23.     fileList = [x for x in contentList if os.path.isfile(x)]  
    24.     print(' File included in current dir: ')  
    25.     for x in fileList:  
    26.         print('  %s' %x)  
    27.   
    28. def fileSearch(name, dir):  
    29.     nameStr = str(name)  
    30.     if(nameStr == '' or nameStr == None):  
    31.         print('Name is error, plz input again')  
    32.     else:  
    33.         #获取当前目录下的所有文件和目录名  
    34.         contentList = os.listdir(dir)  
    35.           
    36.         #搜索当前目录下的文件  
    37.                 <span style="color:#FF0000;">#fileList = [x for x in contentList if os.path.isfile(x))]</span> <span style="color:#FF0000;">  
    38.                 fileList = [x for x in contentList if os.path.isfile(os.path.join(dir, x))]</span>  
    39.         for f in fileList:  
    40.             if(f.find(nameStr, 0, len(f)) != -1):  
    41.                                 f = os.path.join(os.path.abspath(f),f)  
    42.                 print('  %s' %f)  
    43.           
    44.         #在子目录下搜索  
    45.         dirList = [x for x in contentList if os.path.isdir(x)]  
    46.         for d in dirList:  
    47.             dir = os.path.join(dir, d)  
    48.             fileSearch(nameStr, dir)  
    49.           
    50. if __name__ == '__main__':  
    51.     fileSearch('py',dir=os.getcwd())  


    注意红色的那两行!!!

    最开始我用

     
    1. <span style="color:#FF0000;">fileList = [x for x in contentList if os.path.isfile(x))]</span> <span style="color:#FF0000;">  
    2. </span>  

    对搜索到的内容进行判断是否是一个文件,程序只能运行在当前目录下:

     
    1. root@kali:/usr/peic/python# python ./OS_OperationDemo.py  
    2.   /usr/peic/python/OS_OperationDemo.py/OS_OperationDemo.py  
    3.   /usr/peic/python/IO_Demo.py/IO_Demo.py  
    4. root@kali:/usr/peic/python# cd ..  
    5. root@kali:/usr/peic# python ./python/OS_OperationDemo.py  

    在其他目录运行没有结果

    查询发现:

    listdir()只返回文件名,不包含完整路径,在其他目录下测试isfile()当然是False了,需要用os.path.isfile(os.path.join(currentpath, filename)),改为:

     
    1. <span style="color:#FF0000;">fileList = [x for x in contentList if os.path.isfile(os.path.join(dir, x))]</span>  

    能够正常运行:

      1. root@kali:/usr/peic# python ./python/OS_OperationDemo.py  
      1.   /usr/peic/OS_OperationDemo.py/OS_OperationDemo.py  
      2.   /usr/peic/IO_Demo.py/IO_Demo.py  
  • 相关阅读:
    [leetcode]Reverse Words in a String
    [leetcode]ZigZag Conversion
    [leetcode]Gray Code
    [leetcode]Permutation Sequence
    [leetcode]Next Permutation
    [leetcode]PermutationsII
    [leetcode]Add Two Numbers
    Python与PHP通过XMLRPC进行通信
    最近发现了个js传图预览的函数和大家分享下
    百度地图api2.0体验
  • 原文地址:https://www.cnblogs.com/MLing/p/7050893.html
Copyright © 2011-2022 走看看