在python中os是一個非常常用的模塊,下面是對os中方法的總結(實驗為Mac環境)
1 . ?os.name ?:輸出字符串指示使用的平臺,windows是'nt', linux/unix/mac是'posix'
>>> os.name
'posix'
>>>
2 . os.getcwd() :獲取當前目錄
>>> os.getcwd()
'/Users/tp'
>>>
3 . os.system() :執行一條shell
>>> os.system("mkdir tt")
0
>>>
4 . os.listdir( path ) :返回指定path下的所有文件名和目錄名(可以看到剛才創建的tt文件)
>>> os.listdir(os.getcwd() )
['.AB64CF89', '.android', '.bash_history', '.bash_profile', '.bash_profile.pysave', '.CF89AA64', '.CFUserTextEncoding', '.config', '.DS_Store', '.local', '.matplotlib', '.mysql_history', '.rediscli_history', '.rnd', '.ssh', '.subversion', '.Trash', '.vim', '.viminfo', '.vimrc', 'Desktop', 'Documents', 'Downloads', 'dump.rdb', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'PycharmProjects', 'test', 'tt', 'workspace']
>>>
5 . os.remove( file ) ?:刪除文件
6 . os.removedirs( path ) :刪除文件夾
>>> strPath = os.getcwd() +'/tt'
>>> print strPath
/Users/heshan/tt
>>> os.removedirs(strPath)
>>>
7 . os.sep : 可取帶操作系統特定的路徑分割符
8 . os.linesep ?:當前平臺的行分割符
>>> os.sep
'/'
>>> os.linesep
'\n'
>>>
9 . os.path.exists( path ) :檢驗目錄path是否存在
10 . os.path.isdir( path ) :path是否是目錄
10 . os.path.isfile( file ): file是否是文件
>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile(os.getcwd())
False
>>> os.path.exists(os.getcwd())
True
>>>
11 . os.path.getsize( file ): 獲取文件大小
12 . os.path.splitext( file ): 分離文件后綴名
13 . os.path.split( file ): 分離文件名和目錄
14 . os.path.join( path ,file ): 連接目錄和文件名
15 . os.path.dirname( file ): 返回文件目錄
>>> os.path.getsize(os.getcwd())
1156
>>> os.path.splitext(os.getcwd())
('/Users/tp', '')
>>> os.path.split(os.getcwd())
('/Users', 'heshan')
>>> os.path.join(os.getcwd(),'test.in')
'/Users/heshan/test.in'
>>> os.path.dirname(os.getcwd())
'/Users'
>>>