在python中os是一个非常常用的模块,下面是对os中方法的总结(实验为Mac环境)
1 . os.name :输出字符串指示使用的平台,windows是'nt', linux/unix/mac是'posix'
<span style="font-family: FangSong_GB2312;"><span style="font-size:14px;">>>> os.name
'posix'
>>>
</span></span>
2 . os.getcwd() :获取当前目录
<span style="font-family: FangSong_GB2312;"><span style="font-size:14px;">>>> os.getcwd()
'/Users/tp'
>>>
</span></span>
<span style="font-size:14px;">>>> os.system("mkdir tt")
0
>>>
</span>
4 . os.listdir( path ) :返回指定path下的所有文件名和目录名(可以看到刚才创建的tt文件)
<span style="font-size:14px;">>>> 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', <span style="color:#ff0000;background-color: rgb(255, 255, 102);">'tt'</span>, 'workspace']
>>>
</span>
6 . os.removedirs( path ) :删除文件夹
<span style="font-size:14px;">>>> strPath = os.getcwd() +'/tt'
>>> print strPath
/Users/heshan/tt
>>> os.removedirs(strPath)
>>>
</span>
7 . os.sep : 可取带操作系统特定的路径分割符
8 . os.linesep :当前平台的行分割符
<span style="font-size:14px;">>>> os.sep
'/'
>>> os.linesep
'\n'
>>> </span>
10 . os.path.isdir( path ) :path是否是目录
10 . os.path.isfile( file ): file是否是文件
<span style="font-size:14px;">>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile(os.getcwd())
False
>>> os.path.exists(os.getcwd())
True
>>>
</span>
12 . os.path.splitext( file ): 分离文件后缀名
13 . os.path.split( file ): 分离文件名和目录
14 . os.path.join( path ,file ): 连接目录和文件名
15 . os.path.dirname( file ): 返回文件目录
<span style="font-size:14px;">>>> 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'
>>>
</span>