CLH blog AI CV Algorithm

Python os model

2018-06-13
CLH

Python os 模块


Python的os模块包含各种操作系统功能的接口,同时也提供了丰富的文件和目录处理方法。现对常用的方法总结如下:
1、os.name 显示正在使用的平台,Windows为“nt”,linux/Unix为“posix”。

import os
print os.name # python 2.x 

在Windows和Linux/Ubuntu14.04 64bit下的运行结果如下:


另,Linux/Unix Python 还支持os.uname(),返回详细的系统信息(sysname, nodename, release, version, machine):

sys模块中也有类似的方法,sys.platform返回更加详细的信息,Windows返回系统的位数,Linux返回内核的版本:


2、os.listdir(path)列出path目录下的文件,Linux和Windows的path命令不同:

import os
print os.listdir('/home')    # Linux
print os.listdir('f:\\')     #Windows 

结果:

3、os.remove(filename)删除filename文件:

import os    
os.remove('12.txt')   

结果:


4、os.getcwd()返回当前工作目录:

import os     
print os.getcwd()     

结果:



另,列出当前目录下的所有文件:

import os    
print os.listdir(os.getcwd())       结果:    


5、os.getenv(‘env_name’), os.putenv(‘env_name’)读取和设置环境变量:

import os    
print os.getenv('OS') # Windows    

结果:

6、os.system()用来运行shell命令:

import os
os.system('date')       

结果:


7、others:

import os      
os.linesep 		 #显示行终止符,Windows为'\r\n', Linix为'\n',Mac为'\r'            
os.path.split('/home/tmp/test.txt')  #分割目录名和文件名 输出为('/home/tmp','test.txt')        
os.path.isfile(path)   #if is file, return True, else False        
os.path.isdir(path)    #if is dir, return True, else False          
os.path.existe(path)   #path existe or not?     

Comments

Content