python import os模块常用函数

1、os.getcwd()函数

    功能:获取当前目录,python 的工作目


  1. import os
  2.                                                                   
  3. pwd = os.getcwd()
  4.                                                                   
  5. print (pwd)

2、os.name 函数


    功能:获取当前使用的操作系统(获取信息不够详细)

              其中 'nt' 是 windows,'posix' 是 linux 或者 unix


  1. import os
  2.                                                              
  3. name = os.name
  4.                                                              
  5. if name == 'posix':
  6.                                                                  
  7.     print ("this is Linux or Unix")
  8.                                                              
  9. elif name == 'nt':
  10.                                                              
  11.    print ("this is windows")
  12.                                                              
  13. else:
  14.                                                              
  15.    print ("this is other system") 
3、os.remove()函数


    功能:删除指定文件

    eg:删除 file.txt 文件

  1. import os
  2.                                                   
  3. os.remove(’file.txt‘)

4、os.removedirs()函数

    功能:删除指定目录

    eg:删除 file目录


  1. import os
  2.                                                 
  3. os.removedirs(‘file’)

5、os.system()函数

    功能:运行shell命令

    eg:执行ls -a > 1.txt命令


  1. import os
  2.                                            
  3. os.system(‘ls -> 1.txt’)

6、os.mkdir()函数

    功能:创建一个新目录

    eg:创建一个 file 目录


  1. import os
  2.                                  
  3. os.mkdir(‘file’)

7、os.chdir()函数

    功能:改变当前路径到指定路径

    eg:我现在从当前路径到 filepath 所指定的路径下


  1. import os
  2.                       
  3. filepath = '/home'
  4.                       
  5. pwd = os.getcwd()
  6.                       
  7. print (pwd)
  8.                       
  9. os.chdir(filepath)
  10.                       
  11. pwd = os.getcwd()
  12.                       
  13. print (pwd)

8、os.listdir()函数

    功能:返回指定目录下的所有目录和文件

    eg:列出当前目录下的所有文件和目录


  1. import os
  2.              
  3. pwd = os.getcwd()
  4.              
  5. name = os.listdir(pwd)
  6.              
  7. for filename in name:
  8.              
  9.     print (filename)

猜你喜欢

转载自blog.csdn.net/u013455430/article/details/79898600